import { App, Modal, TFile, TFolder, Setting } from 'obsidian';

export interface NotePickerResult {
  title: string;
  files: TFile[];
}

export class NotePickerModal extends Modal {
  private selectedFiles: Set<TFile> = new Set();
  private projectTitle: string = 'My Obsidian Book';
  private onSubmit: (result: NotePickerResult) => void;

  constructor(app: App, defaultTitle: string, onSubmit: (result: NotePickerResult) => void) {
    super(app);
    this.projectTitle = defaultTitle || 'My Obsidian Book';
    this.onSubmit = onSubmit;
  }

  onOpen() {
    const { contentEl } = this;
    contentEl.empty();
    contentEl.createEl('h2', { text: 'Create Physical Book — Select Notes' });

    new Setting(contentEl)
      .setName('Book Title')
      .setDesc('Enter a working title for this book project.')
      .addText((text) =>
        text.setValue(this.projectTitle).onChange((val) => {
          this.projectTitle = val;
        })
      );

    contentEl.createEl('h3', { text: 'Select Notes from Vault' });
    const listContainer = contentEl.createDiv({ cls: 'note-picker-list' });
    listContainer.style.maxHeight = '300px';
    listContainer.style.overflowY = 'auto';
    listContainer.style.border = '1px solid var(--background-modifier-border)';
    listContainer.style.padding = '8px';
    listContainer.style.borderRadius = '4px';

    const allMarkdownFiles = this.app.vault.getMarkdownFiles();

    allMarkdownFiles.forEach((file) => {
      const itemEl = listContainer.createDiv({ cls: 'note-picker-item' });
      itemEl.style.display = 'flex';
      itemEl.style.alignItems = 'center';
      itemEl.style.gap = '8px';
      itemEl.style.padding = '4px 0';

      const checkbox = itemEl.createEl('input', { type: 'checkbox' });
      checkbox.addEventListener('change', () => {
        if (checkbox.checked) {
          this.selectedFiles.add(file);
        } else {
          this.selectedFiles.delete(file);
        }
      });

      itemEl.createEl('span', { text: file.path });
    });

    new Setting(contentEl).addButton((btn) =>
      btn
        .setButtonText('Create Book Project')
        .setCta()
        .onClick(() => {
          if (this.selectedFiles.size === 0) {
            // Default to all active if none checked
            const activeFile = this.app.workspace.getActiveFile();
            if (activeFile) this.selectedFiles.add(activeFile);
          }
          this.close();
          this.onSubmit({
            title: this.projectTitle,
            files: Array.from(this.selectedFiles),
          });
        })
    );
  }

  onClose() {
    const { contentEl } = this;
    contentEl.empty();
  }
}
