"use client";

/**
 * Writing Assistant — Three-panel editor with real-time SEO, LLMO,
 * and humanization scoring. Rich text editing with AI rewrite/expand/simplify.
 */

import { useState, useEffect, useCallback, useRef, useMemo } from "react";
import { useSearchParams } from "next/navigation";
import { useBrand } from "@/context/brand-context";
import { useBackgroundTasks } from "@/lib/stores/task-store";
import { scoreContent, type ContentScores } from "@/lib/services/content-scorer";
import {
  PenTool, Save, Loader2, FileText, Plus, Trash2, Bold, Italic, Heading1, Heading2, Heading3,
  List, ListOrdered, Link2, Quote, Sparkles, CheckCircle2, XCircle, AlertTriangle,
  ChevronRight, ArrowLeft,
} from "lucide-react";
import FeatureGate from "@/components/plan/feature-gate";

interface DocSummary { id: string; title: string; targetKeyword: string | null; grade: string | null; wordCount: number | null; updatedAt: string }

// ── Score Panel ──
function ScoreSection({ label, score, max, factors }: { label: string; score: number; max: number; factors: ContentScores["seo"]["factors"] }) {
  const pct = max > 0 ? Math.round((score / max) * 100) : 0;
  const color = pct >= 75 ? "text-green-600" : pct >= 50 ? "text-amber-600" : "text-red-600";
  return (
    <div className="mb-4">
      <div className="flex items-center justify-between mb-1.5">
        <span className="text-xs font-bold text-slate-700">{label}</span>
        <span className={`text-sm font-bold ${color}`}>{score}/{max}</span>
      </div>
      <div className="space-y-1">
        {factors.map((f, i) => (
          <div key={i} className="flex items-start gap-1.5 text-[11px]">
            {f.status === "pass" ? <CheckCircle2 className="w-3 h-3 text-green-500 mt-0.5 shrink-0" /> :
             f.status === "partial" ? <AlertTriangle className="w-3 h-3 text-amber-500 mt-0.5 shrink-0" /> :
             <XCircle className="w-3 h-3 text-red-400 mt-0.5 shrink-0" />}
            <span className={f.status === "pass" ? "text-slate-500" : "text-slate-700"}>
              {f.name} {f.tip && <span className="text-slate-400">— {f.tip}</span>}
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}

// Writing Assistant is an Agency+ feature. FeatureGate wrapper catches
// direct navigations that bypass the sidebar's locked-click handler.
export default function WritingAssistantPageGated() {
  return (
    <FeatureGate feature="writing_assistant">
      <WritingAssistantPage />
    </FeatureGate>
  );
}

function WritingAssistantPage() {
  const { brand } = useBrand();
  const { addTask, completeTask } = useBackgroundTasks();

  // Document list vs editor
  const [docId, setDocId] = useState<string | null>(null);
  const [docs, setDocs] = useState<DocSummary[]>([]);
  const [docsLoading, setDocsLoading] = useState(true);

  // Deep link support — /writing-assistant?topic=X (sent by Topic Map).
  // Pre-fills the new-doc title + target keyword so the user lands
  // ready to start drafting against that topic.
  const searchParams = useSearchParams();
  const initialTopic = (searchParams.get("topic") || searchParams.get("keyword") || "").trim();

  // Editor state
  const [title, setTitle] = useState(initialTopic || "Untitled Document");
  const [targetKeyword, setTargetKeyword] = useState(initialTopic);
  const [secondaryKws, setSecondaryKws] = useState<string[]>([]);
  const [metaDesc, setMetaDesc] = useState("");
  const editorRef = useRef<HTMLDivElement>(null);
  const [saving, setSaving] = useState(false);
  const [scores, setScores] = useState<ContentScores | null>(null);
  const debounceRef = useRef<ReturnType<typeof setTimeout>>();
  const [aiLoading, setAiLoading] = useState(false);

  // Load documents
  const loadDocs = useCallback(async () => {
    if (!brand?.id) return;
    setDocsLoading(true);
    try { const r = await fetch(`/api/writing-assistant/documents?brandId=${brand.id}`); if (r.ok) { const d = await r.json(); setDocs(d.documents || []); } } finally { setDocsLoading(false); }
  }, [brand.id]);
  useEffect(() => { loadDocs(); }, [loadDocs]);

  // Load a specific document
  async function loadDoc(id: string) {
    const r = await fetch(`/api/writing-assistant/documents/${id}`);
    if (!r.ok) return;
    const { document: d } = await r.json();
    setDocId(d.id); setTitle(d.title); setTargetKeyword(d.targetKeyword || "");
    setSecondaryKws(d.secondaryKeywords || []); setMetaDesc("");
    if (editorRef.current) editorRef.current.innerHTML = d.content || "";
    runScore();
  }

  function newDoc() {
    setDocId(null); setTitle("Untitled Document"); setTargetKeyword(""); setSecondaryKws([]); setMetaDesc("");
    if (editorRef.current) editorRef.current.innerHTML = "";
    setScores(null);
  }

  // Scoring with debounce
  function runScore() {
    clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(() => {
      const html = editorRef.current?.innerHTML || "";
      const text = editorRef.current?.innerText || "";
      setScores(scoreContent(html, text, targetKeyword, secondaryKws, metaDesc));
    }, 300);
  }

  // Save
  async function save() {
    setSaving(true);
    const html = editorRef.current?.innerHTML || "";
    const text = editorRef.current?.innerText || "";
    const s = scores || scoreContent(html, text, targetKeyword, secondaryKws, metaDesc);
    await fetch("/api/writing-assistant/save", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ id: docId, brandId: brand.id, title, content: html, plainText: text, targetKeyword, secondaryKeywords: secondaryKws, seoScore: s.seo.score, llmoScore: s.llmo.score, humanScore: s.human.score, grade: s.grade, wordCount: s.wordCount }),
    }).then((r) => r.json()).then((d) => { if (d.document?.id) setDocId(d.document.id); });
    setSaving(false); loadDocs();
  }

  // Formatting commands
  function fmt(cmd: string, val?: string) { document.execCommand(cmd, false, val); editorRef.current?.focus(); runScore(); }

  // AI rewrite
  async function aiAction(mode: "rewrite" | "expand" | "simplify") {
    const sel = window.getSelection()?.toString();
    if (!sel?.trim()) return;
    setAiLoading(true);
    try {
      const r = await fetch("/api/writing-assistant/ai-rewrite", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ text: sel, mode, keyword: targetKeyword, brandId: brand.id }) });
      if (r.ok) {
        const d = await r.json();
        const replacement = mode === "rewrite" ? d.alternatives?.[0] : mode === "expand" ? d.expanded : d.simplified;
        if (replacement) document.execCommand("insertText", false, replacement);
      }
    } finally { setAiLoading(false); runScore(); }
  }

  async function deleteDoc(id: string) {
    if (!confirm("Delete this document?")) return;
    await fetch(`/api/writing-assistant/documents/${id}`, { method: "DELETE" });
    if (docId === id) newDoc();
    loadDocs();
  }

  const gradeColor = (g: string | null) => !g ? "text-slate-400" : g.startsWith("A") ? "text-green-600 bg-green-50" : g.startsWith("B") ? "text-teal-600 bg-teal-50" : g.startsWith("C") ? "text-amber-600 bg-amber-50" : "text-red-600 bg-red-50";

  // Auto-save every 30s
  useEffect(() => { const id = setInterval(() => { if (editorRef.current?.innerText?.trim()) save(); }, 30000); return () => clearInterval(id); }, [docId, title, targetKeyword, brand.id]);

  // ── Document list view ──
  if (!editorRef.current && !docId && docs.length >= 0 && !title.includes("Untitled")) {
    // Let through to editor
  }

  const showEditor = docId !== null || title !== "Untitled Document" || (editorRef.current?.innerText?.trim());

  return (
    <div className="h-[calc(100vh-theme(spacing.16)-theme(spacing.12))] flex flex-col">
      {/* Top bar */}
      <div className="flex items-center gap-3 border-b border-slate-200 bg-white px-4 py-2.5 shrink-0">
        <button onClick={() => { newDoc(); }} className="flex items-center gap-1 text-xs text-slate-500 hover:text-slate-700"><ArrowLeft className="w-3 h-3" /> Documents</button>
        <span className="text-slate-300">/</span>
        <input value={title} onChange={(e) => setTitle(e.target.value)} className="flex-1 text-sm font-bold text-slate-900 bg-transparent focus:outline-none" />
        {scores && <span className={`text-xs font-bold px-2 py-0.5 rounded ${gradeColor(scores.grade)}`}>{scores.grade}</span>}
        <span className="text-[11px] text-slate-400">{scores?.wordCount || 0} words · {scores?.readingTime || 0} min</span>
        <button onClick={save} disabled={saving} className="flex items-center gap-1.5 px-3 py-1.5 bg-slate-900 text-white text-xs font-semibold rounded-lg hover:bg-slate-800 disabled:opacity-50">
          {saving ? <Loader2 className="w-3 h-3 animate-spin" /> : <Save className="w-3 h-3" />} Save
        </button>
      </div>

      <div className="flex-1 flex overflow-hidden">
        {/* Left — Keywords */}
        <aside className="w-[220px] border-r border-slate-200 bg-white p-4 overflow-y-auto shrink-0">
          <label className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1 block">Target Keyword</label>
          <input value={targetKeyword} onChange={(e) => { setTargetKeyword(e.target.value); runScore(); }} placeholder="e.g. hvac repair houston" className="w-full px-2.5 py-1.5 text-xs border border-slate-200 rounded-lg mb-3 focus:outline-none focus:ring-2 focus:ring-blue-500/40" />

          <label className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1 block">Secondary Keywords</label>
          <textarea value={secondaryKws.join("\n")} onChange={(e) => { setSecondaryKws(e.target.value.split("\n").filter(Boolean)); runScore(); }} placeholder="One per line" rows={4} className="w-full px-2.5 py-1.5 text-xs border border-slate-200 rounded-lg mb-3 focus:outline-none focus:ring-2 focus:ring-blue-500/40" />

          <label className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1 block">Meta Description</label>
          <textarea value={metaDesc} onChange={(e) => { setMetaDesc(e.target.value); runScore(); }} placeholder="150-160 characters" rows={3} className="w-full px-2.5 py-1.5 text-xs border border-slate-200 rounded-lg mb-3 focus:outline-none focus:ring-2 focus:ring-blue-500/40" />
          <p className="text-[10px] text-slate-400">{metaDesc.length}/160 chars</p>

          <div className="mt-4 border-t border-slate-100 pt-3">
            <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-2">Saved Documents</p>
            {docsLoading ? <Loader2 className="w-4 h-4 animate-spin text-slate-300" /> : docs.length === 0 ? <p className="text-[10px] text-slate-400">No documents yet</p> : (
              <div className="space-y-1">
                {docs.slice(0, 8).map((d) => (
                  <button key={d.id} onClick={() => loadDoc(d.id)} className={`w-full text-left px-2 py-1.5 rounded text-[11px] truncate hover:bg-slate-50 ${docId === d.id ? "bg-slate-100 font-semibold text-slate-900" : "text-slate-600"}`}>{d.title}</button>
                ))}
              </div>
            )}
            <button onClick={newDoc} className="mt-2 flex items-center gap-1 text-[10px] font-semibold text-brand-600 hover:underline"><Plus className="w-3 h-3" /> New Document</button>
          </div>
        </aside>

        {/* Center — Editor */}
        <div className="flex-1 flex flex-col min-w-0">
          {/* Toolbar */}
          <div className="flex items-center gap-1 px-3 py-1.5 border-b border-slate-200 bg-slate-50 shrink-0 flex-wrap">
            <button onClick={() => fmt("bold")} className="p-1.5 rounded hover:bg-slate-200" title="Bold"><Bold className="w-3.5 h-3.5" /></button>
            <button onClick={() => fmt("italic")} className="p-1.5 rounded hover:bg-slate-200" title="Italic"><Italic className="w-3.5 h-3.5" /></button>
            <span className="w-px h-4 bg-slate-200 mx-1" />
            <button onClick={() => fmt("formatBlock", "h1")} className="p-1.5 rounded hover:bg-slate-200" title="H1"><Heading1 className="w-3.5 h-3.5" /></button>
            <button onClick={() => fmt("formatBlock", "h2")} className="p-1.5 rounded hover:bg-slate-200" title="H2"><Heading2 className="w-3.5 h-3.5" /></button>
            <button onClick={() => fmt("formatBlock", "h3")} className="p-1.5 rounded hover:bg-slate-200" title="H3"><Heading3 className="w-3.5 h-3.5" /></button>
            <span className="w-px h-4 bg-slate-200 mx-1" />
            <button onClick={() => fmt("insertUnorderedList")} className="p-1.5 rounded hover:bg-slate-200" title="Bullet list"><List className="w-3.5 h-3.5" /></button>
            <button onClick={() => fmt("insertOrderedList")} className="p-1.5 rounded hover:bg-slate-200" title="Numbered list"><ListOrdered className="w-3.5 h-3.5" /></button>
            <button onClick={() => { const url = prompt("URL:"); if (url) fmt("createLink", url); }} className="p-1.5 rounded hover:bg-slate-200" title="Link"><Link2 className="w-3.5 h-3.5" /></button>
            <button onClick={() => fmt("formatBlock", "blockquote")} className="p-1.5 rounded hover:bg-slate-200" title="Quote"><Quote className="w-3.5 h-3.5" /></button>
            <span className="w-px h-4 bg-slate-200 mx-1" />
            <button onClick={() => aiAction("rewrite")} disabled={aiLoading} className="flex items-center gap-1 px-2 py-1 text-[10px] font-semibold text-violet-600 bg-violet-50 rounded hover:bg-violet-100 disabled:opacity-50">
              {aiLoading ? <Loader2 className="w-3 h-3 animate-spin" /> : <Sparkles className="w-3 h-3" />} Rewrite
            </button>
            <button onClick={() => aiAction("expand")} disabled={aiLoading} className="flex items-center gap-1 px-2 py-1 text-[10px] font-semibold text-teal-600 bg-teal-50 rounded hover:bg-teal-100 disabled:opacity-50">Expand</button>
            <button onClick={() => aiAction("simplify")} disabled={aiLoading} className="flex items-center gap-1 px-2 py-1 text-[10px] font-semibold text-amber-600 bg-amber-50 rounded hover:bg-amber-100 disabled:opacity-50">Simplify</button>
          </div>

          {/* Content editable area */}
          <div className="flex-1 overflow-y-auto p-6 bg-white">
            <div ref={editorRef} contentEditable suppressContentEditableWarning onInput={runScore}
              className="prose prose-sm max-w-none min-h-[400px] focus:outline-none [&>h1]:text-2xl [&>h1]:font-bold [&>h2]:text-xl [&>h2]:font-bold [&>h3]:text-lg [&>h3]:font-semibold"
              data-placeholder="Start writing..."
            />
          </div>
        </div>

        {/* Right — Scores */}
        <aside className="w-[240px] border-l border-slate-200 bg-white p-4 overflow-y-auto shrink-0">
          {scores ? (
            <>
              <div className="text-center mb-4 pb-3 border-b border-slate-100">
                <span className={`text-3xl font-bold ${gradeColor(scores.grade)}`}>{scores.grade}</span>
                <p className="text-[10px] text-slate-400 mt-0.5">Content Grade</p>
              </div>
              <ScoreSection label="SEO Score" score={scores.seo.score} max={scores.seo.max} factors={scores.seo.factors} />
              <ScoreSection label="LLMO Score" score={scores.llmo.score} max={scores.llmo.max} factors={scores.llmo.factors} />
              <ScoreSection label="Humanization" score={scores.human.score} max={scores.human.max} factors={scores.human.factors} />
            </>
          ) : (
            <div className="text-center py-8">
              <PenTool className="w-8 h-8 text-slate-200 mx-auto mb-2" />
              <p className="text-xs text-slate-400">Start writing to see scores</p>
            </div>
          )}
        </aside>
      </div>
    </div>
  );
}
