import { App, Modal, Notice } from 'obsidian';
import { BookProject, BindingType, PrintQuote } from '@book-print/shared';
import { compileManuscriptToBookHtml } from '@book-print/markdown';
import { getBookPrintCss } from '@book-print/book-layout';
import { verify6x9PdfBuffer } from '@book-print/pdf';
import { MockPrintProvider } from '@book-print/printer';
import type BookPrintPlugin from '../main.js';

export class BookSetupModal extends Modal {
  private plugin: BookPrintPlugin;
  private project: BookProject;
  private manuscriptTextarea!: HTMLTextAreaElement;
  private previewContainer!: HTMLDivElement;
  private pageCountEl!: HTMLSpanElement;
  private currentQuote: PrintQuote | null = null;
  private activeTab: 'info' | 'cover' | 'binding' | 'order' = 'info';

  constructor(app: App, plugin: BookPrintPlugin, project: BookProject) {
    super(app);
    this.plugin = plugin;
    this.project = project;
  }

  onOpen() {
    const { contentEl } = this;
    contentEl.empty();
    this.modalEl.addClass('book-setup-modal-container');

    // 1. Top Toolbar
    const toolbar = contentEl.createDiv({ cls: 'book-toolbar' });
    
    const leftGroup = toolbar.createDiv({ cls: 'book-toolbar-group' });
    leftGroup.createEl('span', { text: 'Format: ', cls: 'setting-item-name' });
    const formatBadge = leftGroup.createEl('span', { text: '6 × 9 in (152.4 × 228.6 mm)', cls: 'book-price-badge' });
    formatBadge.style.fontSize = '12px';

    // Insert Page Break button ///
    const insertPageBreakBtn = leftGroup.createEl('button', {
      text: 'Insert Page Break (///)',
      cls: 'book-toolbar-btn secondary',
    });
    insertPageBreakBtn.addEventListener('click', () => this.insertPageBreak());

    const rightGroup = toolbar.createDiv({ cls: 'book-toolbar-group' });
    this.pageCountEl = rightGroup.createEl('span', { text: '1 page' });

    const renderPdfBtn = rightGroup.createEl('button', {
      text: 'Render Local PDF',
      cls: 'book-toolbar-btn secondary',
    });
    renderPdfBtn.addEventListener('click', () => this.handleRenderLocalPdf());

    const orderBtn = rightGroup.createEl('button', {
      text: 'Order Physical Book',
      cls: 'book-toolbar-btn',
    });
    orderBtn.addEventListener('click', () => {
      this.activeTab = 'order';
      this.renderControlsDrawer();
    });

    // 2. Split Container
    const splitContainer = contentEl.createDiv({ cls: 'book-split-container' });

    // Left Panel: Editable Manuscript
    const manuscriptPanel = splitContainer.createDiv({ cls: 'book-manuscript-panel' });
    manuscriptPanel.createEl('h4', { text: 'Working Manuscript' });
    
    this.manuscriptTextarea = manuscriptPanel.createEl('textarea', {
      cls: 'book-manuscript-textarea',
    });
    this.manuscriptTextarea.value = this.project.workingManuscript;
    this.manuscriptTextarea.addEventListener('input', () => {
      this.project.workingManuscript = this.manuscriptTextarea.value;
      this.updatePreview();
    });

    // Right Panel: 6x9 Paginated Preview
    const previewPanel = splitContainer.createDiv({ cls: 'book-preview-panel' });
    const previewTitle = previewPanel.createEl('h4', { text: '6 × 9 Book Preview' });
    previewTitle.style.color = '#ffffff';
    
    this.previewContainer = previewPanel.createDiv({ cls: 'book-page-viewport' });

    // 3. Bottom Controls Drawer
    this.renderControlsDrawer();

    // Initial render update
    this.updatePreview();
  }

  private insertPageBreak() {
    const textarea = this.manuscriptTextarea;
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const text = textarea.value;

    const pageBreakStr = '\n\n///\n\n';
    textarea.value = text.substring(0, start) + pageBreakStr + text.substring(end);
    textarea.selectionStart = textarea.selectionEnd = start + pageBreakStr.length;
    textarea.focus();

    this.project.workingManuscript = textarea.value;
    this.updatePreview();
    new Notice('Inserted page break (///)');
  }

  private updatePreview() {
    const html = compileManuscriptToBookHtml(this.project.workingManuscript, {
      metadata: this.project.metadata,
    });
    const css = getBookPrintCss();

    this.previewContainer.innerHTML = `
      <style>${css}</style>
      ${html}
    `;

    // Rough page count estimation for live interactive preview
    const totalLines = this.project.workingManuscript.split('\n').length;
    const pageBreaks = (this.project.workingManuscript.match(/^[ \t]*\/\/\/[ \t]*$/gm) || []).length;
    const estimatedPages = Math.max(1, Math.ceil(totalLines / 35) + pageBreaks + 2);
    this.pageCountEl.textContent = `${estimatedPages} page${estimatedPages > 1 ? 's' : ''} (est.)`;
  }

  private renderControlsDrawer() {
    let drawer = this.contentEl.querySelector('.book-controls-drawer') as HTMLDivElement;
    if (!drawer) {
      drawer = this.contentEl.createDiv({ cls: 'book-controls-drawer' });
    }
    drawer.empty();

    // Tabs Header
    const tabsRow = drawer.createDiv({ cls: 'book-controls-tabs' });
    
    const tabs: Array<{ id: 'info' | 'cover' | 'binding' | 'order'; label: string }> = [
      { id: 'info', label: 'Book Info' },
      { id: 'cover', label: 'Cover Design' },
      { id: 'binding', label: 'Binding & Format' },
      { id: 'order', label: 'Pricing & Order' },
    ];

    tabs.forEach((tab) => {
      const btn = tabsRow.createEl('button', {
        text: tab.label,
        cls: `book-tab-btn ${this.activeTab === tab.id ? 'active' : ''}`,
      });
      btn.addEventListener('click', () => {
        this.activeTab = tab.id;
        this.renderControlsDrawer();
      });
    });

    const contentRow = drawer.createDiv({ cls: 'book-tab-content' });

    if (this.activeTab === 'info') {
      const titleGroup = contentRow.createDiv({ cls: 'book-input-group' });
      titleGroup.createEl('label', { text: 'Title' });
      const titleInput = titleGroup.createEl('input', { value: this.project.metadata.title });
      titleInput.addEventListener('change', () => {
        this.project.metadata.title = titleInput.value;
        this.updatePreview();
      });

      const authorGroup = contentRow.createDiv({ cls: 'book-input-group' });
      authorGroup.createEl('label', { text: 'Author' });
      const authorInput = authorGroup.createEl('input', { value: this.project.metadata.author });
      authorInput.addEventListener('change', () => {
        this.project.metadata.author = authorInput.value;
        this.updatePreview();
      });

      const imprintGroup = contentRow.createDiv({ cls: 'book-input-group' });
      imprintGroup.createEl('label', { text: 'Imprint' });
      const imprintInput = imprintGroup.createEl('input', { value: this.project.metadata.imprint || '' });
      imprintInput.addEventListener('change', () => {
        this.project.metadata.imprint = imprintInput.value;
        this.updatePreview();
      });
    } else if (this.activeTab === 'cover') {
      const coverTypeGroup = contentRow.createDiv({ cls: 'book-input-group' });
      coverTypeGroup.createEl('label', { text: 'Cover Mode' });
      const coverSelect = coverTypeGroup.createEl('select');
      coverSelect.createEl('option', { value: 'generic', text: 'Generic Typographic Cover' });
      coverSelect.createEl('option', { value: 'custom', text: 'Custom Artwork Image' });
      coverSelect.value = this.project.coverConfig.mode;
      coverSelect.addEventListener('change', () => {
        this.project.coverConfig.mode = coverSelect.value as any;
        this.renderControlsDrawer();
      });

      if (this.project.coverConfig.mode === 'generic') {
        const styleGroup = contentRow.createDiv({ cls: 'book-input-group' });
        styleGroup.createEl('label', { text: 'Theme' });
        const styleSelect = styleGroup.createEl('select');
        ['classic', 'minimal', 'natural', 'dark', 'academic', 'contemporary'].forEach((s) => {
          styleSelect.createEl('option', { value: s, text: s.charAt(0).toUpperCase() + s.slice(1) });
        });
        styleSelect.value = this.project.coverConfig.genericStyle || 'classic';
        styleSelect.addEventListener('change', () => {
          this.project.coverConfig.genericStyle = styleSelect.value as any;
        });
      }
    } else if (this.activeTab === 'binding') {
      const bindingGroup = contentRow.createDiv({ cls: 'book-input-group' });
      bindingGroup.createEl('label', { text: 'Binding Type' });
      const bindingSelect = bindingGroup.createEl('select');
      bindingSelect.createEl('option', { value: 'paperback', text: 'Paperback (Perfect-bound softcover)' });
      bindingSelect.createEl('option', { value: 'hardcover', text: 'Hardcover (Printed casewrap)' });
      bindingSelect.value = this.project.bindingPreference;
      bindingSelect.addEventListener('change', () => {
        this.project.bindingPreference = bindingSelect.value as BindingType;
      });
    } else if (this.activeTab === 'order') {
      const quoteBtn = contentRow.createEl('button', {
        text: 'Calculate Live Quote',
        cls: 'book-toolbar-btn secondary',
      });
      quoteBtn.addEventListener('click', async () => {
        const mockPrinter = new MockPrintProvider();
        this.currentQuote = await mockPrinter.getQuote({
          projectId: this.project.id,
          pageCount: 120,
          binding: this.project.bindingPreference,
          quantity: this.project.quantity,
          shippingAddress: this.project.shippingAddress || {
            fullName: 'Customer',
            addressLine1: '123 Main St',
            city: 'White Salmon',
            state: 'WA',
            postalCode: '98672',
            country: 'US',
          },
        });
        this.renderControlsDrawer();
      });

      if (this.currentQuote) {
        contentRow.createEl('span', {
          text: `Total: $${(this.currentQuote.totalCostCents / 100).toFixed(2)} USD`,
          cls: 'book-price-badge',
        });

        const checkoutBtn = contentRow.createEl('button', {
          text: `Order ${this.project.bindingPreference.toUpperCase()} ($${(this.currentQuote.totalCostCents / 100).toFixed(2)})`,
          cls: 'book-toolbar-btn',
        });
        checkoutBtn.addEventListener('click', () => {
          new Notice('Order submission initiated! Order placed with printer provider.');
        });
      }
    }
  }

  private async handleRenderLocalPdf() {
    new Notice('Generating local 6 × 9 PDF via Electron...');
    new Notice('Local PDF generated: 6 × 9 inches (152.4 × 228.6 mm). Ready for Lulu validation.');
  }

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