import { Plugin, Notice, TFile } from 'obsidian';
import {
  PluginSettings,
  DEFAULT_PLUGIN_SETTINGS,
  BookProject,
} from '@book-print/shared';
import { BookPrintSettingsTab } from './settings/BookPrintSettingsTab.js';
import { NotePickerModal } from './ui/NotePickerModal.js';
import { BookSetupModal } from './views/BookSetupModal.js';

export default class BookPrintPlugin extends Plugin {
  pluginSettings!: PluginSettings;

  async onload() {
    await this.loadSettings();

    // 1. Register Ribbon Icon
    this.addRibbonIcon('book', 'Create Physical Book (6×9)', () => {
      this.launchBookCreation();
    });

    // 2. Register Command Palette Item
    this.addCommand({
      id: 'create-physical-book',
      name: 'Create Physical Book',
      callback: () => {
        this.launchBookCreation();
      },
    });

    // 3. Register Plugin Settings Tab
    this.addSettingTab(new BookPrintSettingsTab(this.app, this));

    console.log('Book Print Obsidian Plugin loaded successfully.');
  }

  onunload() {
    console.log('Book Print Obsidian Plugin unloaded.');
  }

  async loadSettings() {
    this.pluginSettings = Object.assign({}, DEFAULT_PLUGIN_SETTINGS, await this.loadData());
  }

  async saveSettings() {
    await this.saveData(this.pluginSettings);
  }

  private async launchBookCreation() {
    const activeFile = this.app.workspace.getActiveFile();

    if (activeFile && activeFile.extension === 'md') {
      // Launch from current note directly
      const content = await this.app.vault.read(activeFile);
      const project = this.createNewBookProject([activeFile.path], content, activeFile.basename);
      new BookSetupModal(this.app, this, project).open();
    } else {
      // Launch note picker modal for multi-note / folder selection
      new NotePickerModal(this.app, 'My Obsidian Book', async (result) => {
        const contents: string[] = [];
        for (const file of result.files) {
          const fileText = await this.app.vault.read(file);
          contents.push(`# ${file.basename}\n\n${fileText}`);
        }
        const combinedManuscript = contents.join('\n\n///\n\n');
        const project = this.createNewBookProject(
          result.files.map((f) => f.path),
          combinedManuscript,
          result.title
        );
        new BookSetupModal(this.app, this, project).open();
      }).open();
    }
  }

  private createNewBookProject(
    sourcePaths: string[],
    workingManuscript: string,
    title: string
  ): BookProject {
    return {
      id: `project-${Date.now()}-${Math.random().toString(36).substring(2, 7)}`,
      title: title || 'Untitled Book',
      sourceNotePaths: sourcePaths,
      workingManuscript,
      metadata: {
        title: title || 'Untitled Book',
        author: this.pluginSettings.defaultAuthorName || 'Author Name',
        imprint: this.pluginSettings.defaultPublisherImprint || '',
        copyrightHolder: this.pluginSettings.defaultCopyrightHolder || this.pluginSettings.defaultAuthorName,
        copyrightYear: new Date().getFullYear(),
        website: this.pluginSettings.defaultWebsite || '',
        publisherContact: this.pluginSettings.defaultPublisherContact || '',
        includeTitlePage: true,
        includeCopyrightPage: true,
      },
      coverConfig: {
        mode: 'generic',
        genericStyle: 'classic',
      },
      bindingPreference: 'paperback',
      quantity: 1,
      shippingAddress: this.pluginSettings.defaultShippingAddress,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
  }
}
