'use client';

import React, { useState } from 'react';
import { BookProject } from '@/lib/types';
import { FileText, FileType, Printer, X, Download, Book, FileJson } from 'lucide-react';

interface ExportModalProps {
  isOpen: boolean;
  onClose: () => void;
  project: BookProject;
  onPrint: (options: { includeCover: boolean, includeTOC: boolean }) => void;
}

type ExportFormat = 'pdf' | 'word' | 'epub' | 'markdown';
type PageSize = 'A4' | 'A5' | 'Letter';

const ExportModal: React.FC<ExportModalProps> = ({ isOpen, onClose, project, onPrint }) => {
  const [format, setFormat] = useState<ExportFormat>('pdf');
  const [pageSize, setPageSize] = useState<PageSize>('A4');
  const [includeCover, setIncludeCover] = useState(true);
  const [includeTOC, setIncludeTOC] = useState(true);

  if (!isOpen) return null;

  const generateContentHTML = () => {
    let html = `
      <!DOCTYPE html>
      <html lang="fr">
      <head>
        <meta charset="UTF-8">
        <title>${project.title}</title>
        <style>
            body { font-family: 'Times New Roman', serif; line-height: 1.5; color: #000; margin: 0; padding: 0; }
            h1, h2, h3 { color: #000; page-break-after: avoid; }
            .chapter { page-break-before: always; }
            .title-page { text-align: center; page-break-after: always; display: flex; flex-direction: column; justify-content: center; height: 90vh; }
            .toc { page-break-after: always; }
            p { margin-bottom: 1em; text-align: justify; }
            a { color: #000; text-decoration: none; }
            ul { list-style-type: none; padding: 0; }
            li { margin-bottom: 0.5em; }
        </style>
      </head>
      <body>
    `;

    if (includeCover) {
      html += `
        <div class="title-page">
          <h1 style="font-size: 3em; margin-bottom: 0.5em;">${project.title}</h1>
          <h2 style="font-size: 1.5em; font-weight: normal;">${project.author}</h2>
        </div>
      `;
    }

    if (includeTOC) {
      html += `<div class="toc"><h2>Table des Matières</h2><ul>`;
      project.chapters.forEach((chap, idx) => {
        html += `<li><a href="#chap-${idx}">${chap.title}</a></li>`;
      });
      html += `</ul></div>`;
    }

    project.chapters.forEach((chap, idx) => {
      html += `
        <div class="chapter" id="chap-${idx}">
          <h2>${chap.title}</h2>
          ${chap.content}
        </div>
      `;
    });

    html += `</body></html>`;
    return html;
  };

  const handleExport = () => {
    const filename = project.title.replace(/[^a-z0-9]/gi, '_').toLowerCase();

    if (format === 'pdf') {
      // Open print dialog with the formatted content
      const content = generateContentHTML();
      const printWindow = window.open('', '_blank');
      if (printWindow) {
        printWindow.document.write(content);
        printWindow.document.close();
        printWindow.focus();
        setTimeout(() => {
          printWindow.print();
        }, 300);
      }
      onClose();
    }
    else if (format === 'word') {
      // Export as HTML with specific Word namespaces -> interpreted as doc by Word
      const content = generateContentHTML();
      const blob = new Blob(['\ufeff', content], {
        type: 'application/msword'
      });
      downloadBlob(blob, `${filename}.doc`);
    }
    else if (format === 'epub') {
      // Export as a single XHTML file (Ebook ready)
      const content = generateContentHTML();
      const blob = new Blob([content], {
        type: 'application/xhtml+xml'
      });
      downloadBlob(blob, `${filename}.xhtml`);
    }
    else if (format === 'markdown') {
      let md = `# ${project.title}\nBy ${project.author}\n\n`;
      project.chapters.forEach(c => {
        // Very basic HTML to Text conversion
        const text = c.content.replace(/<[^>]+>/g, '\n');
        md += `## ${c.title}\n\n${text}\n\n---\n\n`;
      });
      const blob = new Blob([md], { type: 'text/markdown' });
      downloadBlob(blob, `${filename}.md`);
    }
  };

  const downloadBlob = (blob: Blob, name: string) => {
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = name;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    onClose();
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm animate-in fade-in duration-200 no-print">
      <div className="bg-white rounded-xl shadow-2xl w-[600px] overflow-hidden flex flex-col max-h-[90vh]">

        {/* Header */}
        <div className="bg-slate-900 text-white p-6 flex justify-between items-center">
          <div>
            <h2 className="text-xl font-bold flex items-center gap-2">
              <Download size={24} /> Exporter le livre
            </h2>
            <p className="text-slate-400 text-sm mt-1">{project.title}</p>
          </div>
          <button onClick={onClose} className="text-slate-400 hover:text-white transition-colors">
            <X size={24} />
          </button>
        </div>

        {/* Body */}
        <div className="p-6 overflow-y-auto flex-1">

          {/* Format Selection */}
          <div className="grid grid-cols-2 gap-4 mb-8">
            <button
              onClick={() => setFormat('pdf')}
              className={`p-4 rounded-lg border-2 flex flex-col items-center gap-3 transition-all ${format === 'pdf' ? 'border-blue-600 bg-blue-50 text-blue-800' : 'border-slate-200 hover:border-slate-300 text-slate-600'}`}
            >
              <Printer size={32} />
              <div className="font-semibold">PDF (Impression)</div>
            </button>

            <button
              onClick={() => setFormat('word')}
              className={`p-4 rounded-lg border-2 flex flex-col items-center gap-3 transition-all ${format === 'word' ? 'border-blue-600 bg-blue-50 text-blue-800' : 'border-slate-200 hover:border-slate-300 text-slate-600'}`}
            >
              <FileText size={32} />
              <div className="font-semibold">Microsoft Word</div>
            </button>

            <button
              onClick={() => setFormat('epub')}
              className={`p-4 rounded-lg border-2 flex flex-col items-center gap-3 transition-all ${format === 'epub' ? 'border-blue-600 bg-blue-50 text-blue-800' : 'border-slate-200 hover:border-slate-300 text-slate-600'}`}
            >
              <Book size={32} />
              <div className="font-semibold">EPUB / Ebook</div>
            </button>

            <button
              onClick={() => setFormat('markdown')}
              className={`p-4 rounded-lg border-2 flex flex-col items-center gap-3 transition-all ${format === 'markdown' ? 'border-blue-600 bg-blue-50 text-blue-800' : 'border-slate-200 hover:border-slate-300 text-slate-600'}`}
            >
              <FileJson size={32} />
              <div className="font-semibold">Markdown</div>
            </button>
          </div>

          {/* Options Section */}
          <div className="bg-slate-50 rounded-lg p-5 border border-slate-200">
            <h3 className="text-sm font-bold text-slate-500 uppercase tracking-wider mb-4">
              Paramètres d'exportation ({format.toUpperCase()})
            </h3>

            <div className="space-y-4">
              {format === 'pdf' && (
                <div className="flex items-center justify-between">
                  <div className="flex flex-col">
                    <label className="text-slate-700 font-medium">Format du papier</label>
                    <span className="text-xs text-slate-400">Géré par l'imprimante (A4, A5...)</span>
                  </div>
                  <div className="bg-slate-200 px-3 py-1 rounded text-xs font-mono text-slate-600">Auto</div>
                </div>
              )}

              <div className="flex items-center justify-between">
                <label className="text-slate-700 font-medium cursor-pointer" htmlFor="cover">Inclure la page de titre</label>
                <input
                  id="cover"
                  type="checkbox"
                  checked={includeCover}
                  onChange={(e) => setIncludeCover(e.target.checked)}
                  className="w-5 h-5 rounded border-slate-300 text-blue-600 focus:ring-blue-500"
                />
              </div>

              <div className="flex items-center justify-between">
                <label className="text-slate-700 font-medium cursor-pointer" htmlFor="toc">Générer la table des matières</label>
                <input
                  id="toc"
                  type="checkbox"
                  checked={includeTOC}
                  onChange={(e) => setIncludeTOC(e.target.checked)}
                  className="w-5 h-5 rounded border-slate-300 text-blue-600 focus:ring-blue-500"
                />
              </div>

              {format === 'epub' && (
                <p className="text-xs text-amber-600 bg-amber-50 p-2 rounded mt-2">
                  Note: L'export EPUB génère un fichier XHTML optimisé prêt à être converti par Calibre ou Kindle Previewer.
                </p>
              )}
            </div>
          </div>
        </div>

        {/* Footer */}
        <div className="p-4 border-t border-slate-200 bg-slate-50 flex justify-end gap-3">
          <button
            onClick={onClose}
            className="px-5 py-2 text-slate-600 hover:bg-slate-200 rounded-lg font-medium transition-colors"
          >
            Annuler
          </button>
          <button
            onClick={handleExport}
            className="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-medium shadow-md transition-all flex items-center gap-2"
          >
            {format === 'pdf' ? <Printer size={18} /> : <Download size={18} />}
            {format === 'pdf' ? 'Imprimer / Enregistrer PDF' : `Télécharger .${format === 'word' ? 'doc' : format === 'epub' ? 'xhtml' : 'md'}`}
          </button>
        </div>
      </div>
    </div>
  );
};

export default ExportModal;