'use client';
import { useState, useMemo, useCallback, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { ArrowLeft, Download, ChevronDown, BookOpen, Share2, Edit3, Save, RefreshCw, Eye, EyeOff, CheckCircle } from 'lucide-react';
import ReactMarkdown from 'react-markdown';
import toast from 'react-hot-toast';
import LoadingSpinner from './LoadingSpinner';
import { exportToPDF, exportToDOCX, exportToMarkdown, exportToText } from '@/utils/pdfExport';
import { getSportEmoji } from '@/utils/analytics';
import { book as bookApi } from '@/utils/api';

interface Props {
  bookDraft: string;
  client: { name: string; bookTitle: string; sport: string };
  clientId: string;
  onBack: () => void;
}

const EXPORT_FORMATS = [
  { label: 'PDF',        value: 'pdf', icon: '📄' },
  { label: 'Word Doc',   value: 'doc', icon: '📝' },
  { label: 'Markdown',   value: 'md',  icon: '⬇️' },
  { label: 'Plain Text', value: 'txt', icon: '📃' },
];

const PART_COLORS: Record<number, string> = { 1: '#6366f1', 2: '#a855f7', 3: '#f59e0b', 4: '#10b981' };

export default function BookPreview({ bookDraft: initialDraft, client, clientId, onBack }: Props) {
  const [bookDraft, setBookDraft]     = useState(initialDraft);
  const [showExport, setShowExport]   = useState(false);
  const [activeChapter, setActiveChapter] = useState(0);
  const [editMode, setEditMode]       = useState(false);
  const [editContent, setEditContent] = useState('');
  const [saving, setSaving]           = useState(false);
  const [saved, setSaved]             = useState(false);
  const [regenerating, setRegenerating] = useState(false);
  const [showFullBook, setShowFullBook] = useState(false);
  const autoSaveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);

  // ── Parse chapters ──────────────────────────────────────────────────────────
  const chapters = useMemo(() => {
    const lines = bookDraft.split('\n');
    const result: { title: string; content: string; num: number; part: number }[] = [];
    let current: { title: string; lines: string[]; num: number; part: number } | null = null;
    let currentPart = 1;

    for (const line of lines) {
      if (/^## PART (\d)/.test(line)) {
        const m = line.match(/^## PART (\d)/);
        if (m) currentPart = parseInt(m[1]);
      } else if (/^### Chapter (\d+):/.test(line)) {
        if (current) result.push({ title: current.title, content: current.lines.join('\n').trim(), num: current.num, part: current.part });
        const m = line.match(/^### Chapter (\d+): (.+)/);
        current = { title: m ? m[2] : line.replace(/^###\s*/, ''), lines: [], num: m ? parseInt(m[1]) : result.length + 1, part: currentPart };
      } else if (/^### /.test(line) && !current) {
        current = { title: line.replace(/^###\s*/, ''), lines: [], num: result.length + 1, part: currentPart };
      } else if (current) {
        current.lines.push(line);
      }
    }
    if (current && current.lines.length > 0) result.push({ title: current.title, content: current.lines.join('\n').trim(), num: current.num, part: current.part });
    return result.length > 0 ? result : [{ title: client.bookTitle, content: bookDraft, num: 1, part: 1 }];
  }, [bookDraft, client.bookTitle]);

  const currentChapter = chapters[activeChapter];

  // ── Edit mode ───────────────────────────────────────────────────────────────
  const startEdit = () => {
    setEditContent(currentChapter?.content || '');
    setEditMode(true);
  };

  const handleEditChange = (val: string) => {
    setEditContent(val);
    setSaved(false);
    if (autoSaveTimer.current) clearTimeout(autoSaveTimer.current);
    autoSaveTimer.current = setTimeout(() => autoSave(val), 3000);
  };

  const autoSave = useCallback(async (content: string) => {
    if (!currentChapter) return;
    // Replace chapter content in full draft
    const newDraft = bookDraft.replace(currentChapter.content, content);
    try {
      await bookApi.save(clientId, newDraft);
      setBookDraft(newDraft);
      setSaved(true);
      setTimeout(() => setSaved(false), 3000);
    } catch { /* silent fail on auto-save */ }
  }, [bookDraft, clientId, currentChapter]);

  const saveEdit = async () => {
    if (!currentChapter) return;
    setSaving(true);
    const newDraft = bookDraft.replace(currentChapter.content, editContent);
    try {
      await bookApi.save(clientId, newDraft);
      setBookDraft(newDraft);
      setEditMode(false);
      toast.success('Chapter saved!');
    } catch { toast.error('Failed to save'); }
    finally { setSaving(false); }
  };

  // ── Regenerate chapter ──────────────────────────────────────────────────────
  const regenerateChapter = async () => {
    if (!currentChapter) return;
    setRegenerating(true);
    try {
      const res = await bookApi.regenerateChapter(clientId, currentChapter.num);
      const newDraft = bookDraft.replace(currentChapter.content, res.content);
      await bookApi.save(clientId, newDraft);
      setBookDraft(newDraft);
      setEditMode(false);
      toast.success('Chapter regenerated from your interview!');
    } catch (err: any) {
      toast.error(err.message || 'Failed to regenerate');
    } finally { setRegenerating(false); }
  };

  // ── Export ──────────────────────────────────────────────────────────────────
  const handleExport = (format: string) => {
    setShowExport(false);
    try {
      switch (format) {
        case 'pdf': exportToPDF(bookDraft, client.bookTitle, client.name); break;
        case 'doc': exportToDOCX(bookDraft, client.bookTitle, client.name); break;
        case 'md':  exportToMarkdown(bookDraft, client.bookTitle, client.name); break;
        case 'txt': exportToText(bookDraft, client.bookTitle, client.name); break;
      }
      toast.success(`Exporting as ${format.toUpperCase()}...`);
    } catch { toast.error('Export failed'); }
  };

  const totalWords = bookDraft.split(/\s+/).filter(Boolean).length;
  const partColor = PART_COLORS[currentChapter?.part || 1];

  return (
    <div className="h-screen flex flex-col" style={{ background: 'var(--bg-secondary)' }}>

      {/* Header */}
      <header className="flex-shrink-0 border-b px-4 py-3 flex items-center gap-3"
        style={{ background: 'var(--bg-card)', borderColor: 'var(--border)' }}>
        <button onClick={onBack} className="btn-ghost p-2 rounded-lg" aria-label="Go back">
          <ArrowLeft className="w-4 h-4" />
        </button>
        <div className="flex items-center gap-2 flex-1 min-w-0">
          <BookOpen className="w-4 h-4 flex-shrink-0" style={{ color: '#6366f1' }} />
          <div className="min-w-0">
            <span className="font-bold text-sm truncate block" style={{ color: 'var(--text-primary)' }}>{client.bookTitle}</span>
            <span className="text-xs" style={{ color: 'var(--text-secondary)' }}>
              {chapters.length} chapters · {totalWords.toLocaleString()} words
            </span>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <AnimatePresence>
            {saved && (
              <motion.span initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
                className="text-xs text-green-500 flex items-center gap-1">
                <CheckCircle className="w-3 h-3" /> Saved
              </motion.span>
            )}
          </AnimatePresence>
          <button onClick={() => setShowFullBook(!showFullBook)}
            className="btn-ghost flex items-center gap-1.5 text-xs py-2">
            {showFullBook ? <EyeOff className="w-3.5 h-3.5" /> : <Eye className="w-3.5 h-3.5" />}
            <span className="hidden sm:inline">{showFullBook ? 'Chapter view' : 'Full book'}</span>
          </button>
          <button onClick={() => navigator.clipboard.writeText(window.location.href).then(() => toast.success('Link copied!'))}
            className="btn-secondary flex items-center gap-1.5 text-xs py-2">
            <Share2 className="w-3.5 h-3.5" />
          </button>
          <div className="relative">
            <button onClick={() => setShowExport(!showExport)}
              className="btn-primary flex items-center gap-1.5 text-xs py-2">
              <Download className="w-3.5 h-3.5" /> Export
              <ChevronDown className={`w-3 h-3 transition-transform ${showExport ? 'rotate-180' : ''}`} />
            </button>
            {showExport && (
              <div className="absolute right-0 top-full mt-1 w-40 rounded-xl shadow-xl border overflow-hidden z-50"
                style={{ background: 'var(--bg-card)', borderColor: 'var(--border)' }}>
                {EXPORT_FORMATS.map(f => (
                  <button key={f.value} onClick={() => handleExport(f.value)}
                    className="w-full px-4 py-2.5 text-left text-xs flex items-center gap-2 transition-colors hover:bg-indigo-50 dark:hover:bg-indigo-900/20"
                    style={{ color: 'var(--text-primary)' }}>
                    <span>{f.icon}</span>{f.label}
                  </button>
                ))}
              </div>
            )}
          </div>
        </div>
      </header>

      <div className="flex-1 flex overflow-hidden">

        {/* ── TOC Sidebar ── */}
        {!showFullBook && (
          <aside className="hidden lg:flex flex-col w-64 border-r flex-shrink-0 overflow-y-auto"
            style={{ borderColor: 'var(--border)', background: 'var(--bg-card)' }}>
            {/* Book cover mini */}
            <div className="m-3 rounded-xl p-4 text-white text-center"
              style={{ background: 'linear-gradient(135deg, #6366f1, #a855f7)' }}>
              <div className="text-3xl mb-2">{getSportEmoji(client.sport)}</div>
              <p className="font-bold text-xs leading-tight">{client.bookTitle}</p>
              <p className="text-xs opacity-75 mt-1">By {client.name}</p>
              <div className="mt-2 text-xs opacity-60">{totalWords.toLocaleString()} words</div>
            </div>

            <div className="px-3 pb-3">
              <p className="text-xs font-semibold uppercase tracking-wider mb-2" style={{ color: 'var(--text-secondary)' }}>
                Contents
              </p>
              {chapters.map((ch, i) => (
                <button key={i} onClick={() => { setActiveChapter(i); setEditMode(false); }}
                  className="w-full text-left px-2.5 py-2 rounded-lg mb-0.5 flex items-center gap-2 transition-all text-xs"
                  style={activeChapter === i
                    ? { background: `${PART_COLORS[ch.part]}15`, color: PART_COLORS[ch.part], fontWeight: 600 }
                    : { color: 'var(--text-secondary)' }}>
                  <span className="w-5 h-5 rounded-full flex items-center justify-center text-xs flex-shrink-0 font-bold"
                    style={{ background: activeChapter === i ? `${PART_COLORS[ch.part]}20` : 'var(--bg-secondary)', color: PART_COLORS[ch.part] }}>
                    {ch.num}
                  </span>
                  <span className="truncate">{ch.title}</span>
                </button>
              ))}
            </div>
          </aside>
        )}

        {/* ── Main Content ── */}
        <main className="flex-1 overflow-y-auto">
          {showFullBook ? (
            // Full book view
            <div className="max-w-3xl mx-auto px-6 py-8">
              <div className="card p-8">
                <ReactMarkdown components={mdComponents}>{bookDraft}</ReactMarkdown>
              </div>
            </div>
          ) : (
            // Chapter view
            <div className="max-w-3xl mx-auto px-4 sm:px-6 py-6">
              {currentChapter && (
                <motion.div key={activeChapter} initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }}>
                  {/* Chapter header */}
                  <div className="flex items-center justify-between mb-4">
                    <div>
                      <span className="text-xs font-bold" style={{ color: partColor }}>
                        Chapter {currentChapter.num} of {chapters.length}
                      </span>
                      <h2 className="text-xl font-bold mt-0.5" style={{ color: 'var(--text-primary)' }}>
                        {currentChapter.title}
                      </h2>
                    </div>
                    <div className="flex items-center gap-2">
                      {!editMode && (
                        <>
                          <button onClick={regenerateChapter} disabled={regenerating}
                            className="btn-ghost flex items-center gap-1.5 text-xs py-2"
                            title="Regenerate from interview">
                            {regenerating ? <LoadingSpinner size="sm" /> : <RefreshCw className="w-3.5 h-3.5" />}
                            <span className="hidden sm:inline">Regenerate</span>
                          </button>
                          <button onClick={startEdit}
                            className="btn-secondary flex items-center gap-1.5 text-xs py-2">
                            <Edit3 className="w-3.5 h-3.5" /> Edit
                          </button>
                        </>
                      )}
                      {editMode && (
                        <>
                          <button onClick={() => setEditMode(false)} className="btn-ghost text-xs py-2">Cancel</button>
                          <button onClick={saveEdit} disabled={saving}
                            className="btn-primary flex items-center gap-1.5 text-xs py-2">
                            {saving ? <LoadingSpinner size="sm" /> : <Save className="w-3.5 h-3.5" />}
                            Save
                          </button>
                        </>
                      )}
                    </div>
                  </div>

                  {/* Content */}
                  <div className="card p-6 sm:p-8">
                    {editMode ? (
                      <textarea
                        value={editContent}
                        onChange={e => handleEditChange(e.target.value)}
                        className="w-full text-sm leading-relaxed outline-none resize-none"
                        style={{ minHeight: '500px', background: 'transparent', color: 'var(--text-primary)', fontFamily: 'Georgia, serif', lineHeight: '1.9' }}
                      />
                    ) : (
                      <div className="prose prose-lg max-w-none">
                        <ReactMarkdown components={mdComponents}>{currentChapter.content}</ReactMarkdown>
                      </div>
                    )}
                  </div>

                  {/* Chapter navigation */}
                  <div className="flex justify-between mt-4">
                    <button onClick={() => { setActiveChapter(Math.max(0, activeChapter - 1)); setEditMode(false); }}
                      disabled={activeChapter === 0}
                      className="btn-secondary disabled:opacity-40 text-sm">
                      ← Previous
                    </button>
                    <span className="text-xs self-center" style={{ color: 'var(--text-secondary)' }}>
                      {activeChapter + 1} / {chapters.length}
                    </span>
                    <button onClick={() => { setActiveChapter(Math.min(chapters.length - 1, activeChapter + 1)); setEditMode(false); }}
                      disabled={activeChapter === chapters.length - 1}
                      className="btn-secondary disabled:opacity-40 text-sm">
                      Next →
                    </button>
                  </div>
                </motion.div>
              )}
            </div>
          )}
        </main>
      </div>
    </div>
  );
}

// ── Markdown render components ─────────────────────────────────────────────────
const mdComponents = {
  h1: ({ children }: any) => <h1 className="text-3xl font-bold mb-3 gradient-text">{children}</h1>,
  h2: ({ children }: any) => <h2 className="text-xl font-bold mt-10 mb-3 pt-6 border-t" style={{ borderColor: 'var(--border)', color: '#6366f1' }}>{children}</h2>,
  h3: ({ children }: any) => <h3 className="text-lg font-bold mt-8 mb-3" style={{ color: 'var(--text-primary)' }}>{children}</h3>,
  p:  ({ children }: any) => <p className="mb-5 leading-relaxed" style={{ color: 'var(--text-primary)', fontFamily: 'Georgia, serif', fontSize: '1.05rem', lineHeight: '1.9' }}>{children}</p>,
  blockquote: ({ children }: any) => (
    <blockquote className="border-l-4 pl-4 my-4 italic" style={{ borderColor: '#6366f1', color: 'var(--text-secondary)' }}>{children}</blockquote>
  ),
  hr: () => <hr className="my-8" style={{ borderColor: 'var(--border)' }} />,
  em: ({ children }: any) => <em style={{ color: 'var(--text-primary)' }}>{children}</em>,
  strong: ({ children }: any) => <strong style={{ color: 'var(--text-primary)' }}>{children}</strong>,
};
