"use client";

import { useState, useEffect, useCallback } from "react";
import { Trash2, Search, Clapperboard, Film, ExternalLink, FileDown, Loader2 } from "lucide-react";
import { toast } from "sonner";
import { STORYBOARD_STYLES } from "@/types/storyboard";
import type { StoryboardOutput } from "@/types/storyboard";
import { formatDate } from "@/lib/utils";

interface StoryboardHistoryRow {
  id: string;
  source_url: string;
  source_platform: string;
  source_title: string;
  style: string;
  length: string;
  language: string;
  output: StoryboardOutput;
  created_at: string;
}

export function StoryboardHistoryTab() {
  const [items, setItems]             = useState<StoryboardHistoryRow[]>([]);
  const [loading, setLoading]         = useState(true);
  const [search, setSearch]           = useState("");
  const [styleFilter, setStyleFilter] = useState("all");
  const [expandedId, setExpandedId]   = useState<string | null>(null);
  const [exportingId, setExportingId] = useState<string | null>(null);

  const fetchItems = useCallback(async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams();
      if (styleFilter !== "all") params.set("style", styleFilter);
      if (search) params.set("search", search);
      const res  = await fetch(`/api/storyboard/history?${params}`);
      const data = await res.json();
      setItems(data.data ?? []);
    } catch {
      toast.error("Gagal memuat riwayat storyboard");
    } finally {
      setLoading(false);
    }
  }, [styleFilter, search]);

  useEffect(() => {
    const t = setTimeout(fetchItems, search ? 400 : 0);
    return () => clearTimeout(t);
  }, [fetchItems, search]);

  async function deleteItem(id: string) {
    if (!confirm("Hapus storyboard ini?")) return;
    try {
      const res = await fetch(`/api/storyboard/history?id=${id}`, { method: "DELETE" });
      if (res.ok) {
        setItems((prev) => prev.filter((i) => i.id !== id));
        toast.success("Storyboard dihapus");
      }
    } catch { toast.error("Gagal hapus"); }
  }

  async function handleExportPdf(item: StoryboardHistoryRow) {
    setExportingId(item.id);
    const toastId = toast.loading("Membuat PDF...");
    try {
      const { exportStoryboardToPdf } = await import("@/lib/pdf-exporter");
      await exportStoryboardToPdf(item.output);
      toast.dismiss(toastId);
      toast.success("PDF berhasil didownload! 📄");
    } catch (e) {
      toast.dismiss(toastId);
      toast.error(`Gagal PDF: ${(e as Error).message}`);
    } finally {
      setExportingId(null);
    }
  }

  const styleOptions = [
    { value: "all", label: "Semua Style" },
    ...Object.entries(STORYBOARD_STYLES).map(([k, v]) => ({ value: k, label: `${v.icon} ${v.label}` })),
  ];

  return (
    <div className="space-y-4">
      {/* Filters */}
      <div className="flex flex-wrap gap-3">
        <div className="relative flex-1 min-w-[200px]">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
          <input
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Cari judul atau platform..."
            className="w-full pl-9 pr-4 py-2 rounded-lg bg-card border border-border focus:border-primary focus:outline-none text-sm"
          />
        </div>
        <select
          value={styleFilter}
          onChange={(e) => setStyleFilter(e.target.value)}
          className="px-3 py-2 rounded-lg bg-card border border-border focus:border-primary focus:outline-none text-sm"
        >
          {styleOptions.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
        </select>
      </div>

      {loading ? (
        <div className="space-y-3">
          {[1, 2, 3].map((i) => (
            <div key={i} className="h-28 rounded-xl animate-pulse"
              style={{ background: "rgba(124,58,237,0.06)", border: "1px solid rgba(124,58,237,0.15)" }} />
          ))}
        </div>
      ) : items.length === 0 ? (
        <div className="text-center py-16 text-muted-foreground">
          <Clapperboard className="w-12 h-12 mx-auto mb-3 opacity-30" />
          <p className="font-medium">Belum ada storyboard</p>
          <p className="text-sm mt-1">Buat storyboard pertamamu dari menu Storyboard!</p>
        </div>
      ) : (
        <div className="space-y-3">
          {items.map((item) => {
            const styleInfo  = STORYBOARD_STYLES[item.style as keyof typeof STORYBOARD_STYLES];
            const meta       = item.output?.metadata;
            const isExpanded = expandedId === item.id;

            return (
              <div
                key={item.id}
                className="rounded-xl overflow-hidden transition-all"
                style={{ background: "rgba(124,58,237,0.05)", border: "1px solid rgba(124,58,237,0.2)" }}
              >
                {/* Header row */}
                <div className="flex items-center gap-3 p-4">
                  <div className="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0 text-xl"
                    style={{ background: "rgba(124,58,237,0.2)" }}>
                    {styleInfo?.icon ?? "🎬"}
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-semibold truncate">{item.source_title ?? "Storyboard"}</p>
                    <div className="flex items-center gap-2 mt-0.5 flex-wrap">
                      <span className="text-xs px-1.5 py-0.5 rounded"
                        style={{ background: "rgba(124,58,237,0.2)", color: "#a78bfa" }}>
                        {styleInfo?.label ?? item.style}
                      </span>
                      <span className="text-xs text-muted-foreground">{item.source_platform}</span>
                      {meta?.totalScenes && (
                        <span className="text-xs text-muted-foreground">
                          <Film className="w-3 h-3 inline mr-0.5" />{meta.totalScenes} scene
                        </span>
                      )}
                      {meta?.estimatedDuration && (
                        <span className="text-xs text-muted-foreground">· {meta.estimatedDuration}</span>
                      )}
                      <span className="text-xs text-muted-foreground ml-auto">{formatDate(item.created_at)}</span>
                    </div>
                  </div>
                </div>

                {/* Expanded: scene preview */}
                {isExpanded && item.output && (
                  <div className="px-4 pb-3 space-y-2 border-t border-violet-500/10 pt-3">
                    <div className="text-xs text-muted-foreground font-semibold mb-1">🪝 Hook</div>
                    <p className="text-sm text-foreground/80 italic line-clamp-2">&ldquo;{item.output.hook}&rdquo;</p>
                    <div className="text-xs text-muted-foreground font-semibold mt-3 mb-1">🎬 Scenes</div>
                    <div className="space-y-1.5">
                      {item.output.scenes.slice(0, 3).map((scene) => (
                        <div key={scene.sceneNumber} className="flex items-start gap-2 text-xs">
                          <span className="w-5 h-5 rounded bg-violet-500/20 text-violet-300 flex items-center justify-center flex-shrink-0 font-bold text-[10px]">
                            {scene.sceneNumber}
                          </span>
                          <div className="flex-1 min-w-0">
                            <span className="font-medium text-foreground/90">{scene.title}</span>
                            <span className="text-muted-foreground"> — {scene.narration?.slice(0, 60)}…</span>
                          </div>
                        </div>
                      ))}
                      {item.output.scenes.length > 3 && (
                        <p className="text-xs text-muted-foreground pl-7">
                          +{item.output.scenes.length - 3} scene lainnya
                        </p>
                      )}
                    </div>
                  </div>
                )}

                {/* Action row */}
                <div className="flex items-center gap-1 px-3 pb-3 pt-1">
                  <button
                    onClick={() => setExpandedId(isExpanded ? null : item.id)}
                    className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs text-muted-foreground hover:text-foreground hover:bg-white/5 transition-colors"
                  >
                    <Film className="w-3.5 h-3.5" />
                    {isExpanded ? "Sembunyikan" : "Lihat Scene"}
                  </button>
                  <a
                    href={item.source_url}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs text-muted-foreground hover:text-foreground hover:bg-white/5 transition-colors"
                  >
                    <ExternalLink className="w-3.5 h-3.5" />Sumber
                  </a>
                  <button
                    onClick={() => handleExportPdf(item)}
                    disabled={exportingId === item.id}
                    className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs text-muted-foreground hover:text-rose-300 hover:bg-rose-500/10 transition-colors disabled:opacity-50"
                  >
                    {exportingId === item.id
                      ? <><Loader2 className="w-3.5 h-3.5 animate-spin" />PDF...</>
                      : <><FileDown className="w-3.5 h-3.5" />PDF</>}
                  </button>
                  <button
                    onClick={() => deleteItem(item.id)}
                    className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs text-muted-foreground hover:text-red-400 hover:bg-red-500/10 transition-colors ml-auto"
                  >
                    <Trash2 className="w-3.5 h-3.5" />Hapus
                  </button>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
