"use client";

import { useState, useEffect, useCallback } from "react";
import { Search, Film, Heart, Trash2, ChevronDown, ChevronUp, Copy, Check } from "lucide-react";
import { toast } from "sonner";
import { formatDate } from "@/lib/utils";
import type { UGCPackage } from "@/types/ugc-generator";

interface UGCHistoryRow {
  id: string;
  product_name: string;
  product_url: string | null;
  platform: string;
  durasi: string;
  gaya_bahasa: string;
  language: string;
  output: UGCPackage;
  is_favorite: boolean;
  created_at: string;
}

function CopyButton({ text }: { text: string }) {
  const [copied, setCopied] = useState(false);
  const handleCopy = async () => {
    await navigator.clipboard.writeText(text);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };
  return (
    <button
      onClick={handleCopy}
      className="p-1.5 rounded-lg text-muted-foreground hover:text-foreground transition-colors"
      title="Copy"
    >
      {copied ? <Check className="w-3.5 h-3.5 text-green-400" /> : <Copy className="w-3.5 h-3.5" />}
    </button>
  );
}

function UGCHistoryCard({ item, onToggleFavorite, onDelete }: {
  item: UGCHistoryRow;
  onToggleFavorite: (id: string, current: boolean) => void;
  onDelete: (id: string) => void;
}) {
  const [expanded, setExpanded] = useState(false);

  const output = item.output;
  const fullScriptText = output?.fullScript ?? "";
  const hookText       = output?.hook ?? "";
  const captionText    = output?.caption ?? "";
  const hashtagsText   = output?.hashtags?.join(" ") ?? "";
  const allText        = [hookText, fullScriptText, captionText, hashtagsText].filter(Boolean).join("\n\n");

  return (
    <div
      className="rounded-2xl overflow-hidden transition-all"
      style={{ background: "rgba(236,72,153,0.05)", border: "1px solid rgba(236,72,153,0.15)" }}
    >
      {/* Header row */}
      <div className="flex items-center gap-3 p-3.5">
        <div
          className="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0 text-xl"
          style={{ background: "rgba(236,72,153,0.15)" }}
        >
          🎭
        </div>

        <div className="flex-1 min-w-0">
          <p className="text-sm font-medium truncate">{item.product_name}</p>
          <p className="text-xs text-muted-foreground mt-0.5">
            {item.platform}
            {item.durasi ? ` · ${item.durasi}` : ""}
            {" · "}{formatDate(item.created_at)}
          </p>
        </div>

        <div className="flex items-center gap-1 flex-shrink-0">
          {/* Favorite */}
          <button
            onClick={() => onToggleFavorite(item.id, item.is_favorite)}
            className="p-1.5 rounded-lg transition-colors"
            title={item.is_favorite ? "Hapus dari favorit" : "Tambah ke favorit"}
          >
            <Heart
              className="w-4 h-4"
              style={{ color: item.is_favorite ? "#f43f5e" : undefined }}
              fill={item.is_favorite ? "#f43f5e" : "none"}
            />
          </button>

          {/* Copy all */}
          <CopyButton text={allText} />

          {/* Delete */}
          <button
            onClick={() => onDelete(item.id)}
            className="p-1.5 rounded-lg text-muted-foreground hover:text-red-400 transition-colors"
            title="Hapus"
          >
            <Trash2 className="w-3.5 h-3.5" />
          </button>

          {/* Expand toggle */}
          <button
            onClick={() => setExpanded((v) => !v)}
            className="p-1.5 rounded-lg text-muted-foreground hover:text-foreground transition-colors"
          >
            {expanded ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
          </button>
        </div>
      </div>

      {/* Expanded detail */}
      {expanded && output && (
        <div className="px-4 pb-4 space-y-4 border-t" style={{ borderColor: "rgba(236,72,153,0.12)" }}>
          {/* Hook */}
          {output.hook && (
            <div className="mt-4">
              <div className="flex items-center justify-between mb-1">
                <span className="text-xs font-semibold uppercase tracking-wide" style={{ color: "#f472b6" }}>Hook</span>
                <CopyButton text={output.hook} />
              </div>
              <p className="text-sm bg-card rounded-lg p-3 italic">&ldquo;{output.hook}&rdquo;</p>
            </div>
          )}

          {/* Script scenes */}
          {Array.isArray(output.script) && output.script.length > 0 && (
            <div>
              <div className="flex items-center justify-between mb-2">
                <span className="text-xs font-semibold uppercase tracking-wide" style={{ color: "#f472b6" }}>
                  Script ({output.script.length} scene)
                </span>
                <CopyButton text={output.fullScript ?? ""} />
              </div>
              <div className="space-y-2">
                {output.script.map((scene, i) => (
                  <div key={i} className="rounded-lg p-3 text-xs space-y-1" style={{ background: "rgba(255,255,255,0.04)" }}>
                    <div className="flex items-center gap-2">
                      <span className="font-mono text-pink-400">[{scene.durasi}]</span>
                      <span className="text-muted-foreground">{scene.aksi}</span>
                    </div>
                    <p className="text-foreground/90 font-medium">{scene.dialog}</p>
                    {scene.visualNote && (
                      <p className="text-muted-foreground italic">📷 {scene.visualNote}</p>
                    )}
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Caption */}
          {output.caption && (
            <div>
              <div className="flex items-center justify-between mb-1">
                <span className="text-xs font-semibold uppercase tracking-wide" style={{ color: "#f472b6" }}>Caption</span>
                <CopyButton text={output.caption} />
              </div>
              <p className="text-sm bg-card rounded-lg p-3 whitespace-pre-wrap">{output.caption}</p>
            </div>
          )}

          {/* Hashtags */}
          {Array.isArray(output.hashtags) && output.hashtags.length > 0 && (
            <div>
              <div className="flex items-center justify-between mb-1">
                <span className="text-xs font-semibold uppercase tracking-wide" style={{ color: "#f472b6" }}>Hashtags</span>
                <CopyButton text={output.hashtags.join(" ")} />
              </div>
              <div className="flex flex-wrap gap-1.5">
                {output.hashtags.map((tag, i) => (
                  <span
                    key={i}
                    className="text-xs px-2 py-0.5 rounded-full"
                    style={{ background: "rgba(236,72,153,0.15)", color: "#f472b6" }}
                  >
                    {tag}
                  </span>
                ))}
              </div>
            </div>
          )}

          {/* CTA */}
          {output.callToAction && (
            <div>
              <span className="text-xs font-semibold uppercase tracking-wide block mb-1" style={{ color: "#f472b6" }}>CTA</span>
              <p className="text-sm bg-card rounded-lg p-3">{output.callToAction}</p>
            </div>
          )}

          {/* Production tips */}
          {Array.isArray(output.tipsProduction) && output.tipsProduction.length > 0 && (
            <div>
              <span className="text-xs font-semibold uppercase tracking-wide block mb-1" style={{ color: "#f472b6" }}>Tips Produksi</span>
              <ul className="space-y-1">
                {output.tipsProduction.map((tip, i) => (
                  <li key={i} className="text-xs text-muted-foreground flex gap-2">
                    <span className="text-pink-400 flex-shrink-0">•</span>
                    {tip}
                  </li>
                ))}
              </ul>
            </div>
          )}

          {/* Model info */}
          <p className="text-[10px] text-muted-foreground/60 pt-1">
            Model: {output.metadata?.model ?? "—"} · {formatDate(output.metadata?.generatedAt ?? item.created_at)}
          </p>
        </div>
      )}
    </div>
  );
}

export function UGCHistoryTab() {
  const [items, setItems]     = useState<UGCHistoryRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch]   = useState("");

  const fetchUGCHistory = useCallback(async () => {
    setLoading(true);
    try {
      const res  = await fetch("/api/history?type=ugc&limit=50");
      const data = await res.json();
      setItems(data.data ?? []);
    } catch {
      toast.error("Gagal memuat riwayat UGC");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => { fetchUGCHistory(); }, [fetchUGCHistory]);

  const handleToggleFavorite = async (id: string, current: boolean) => {
    // Optimistic update
    setItems((prev) =>
      prev.map((item) => item.id === id ? { ...item, is_favorite: !current } : item)
    );
    try {
      const res = await fetch("/api/history", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id, type: "ugc", is_favorite: !current }),
      });
      if (!res.ok) throw new Error();
      toast.success(current ? "Dihapus dari favorit" : "Ditambahkan ke favorit");
    } catch {
      // Rollback
      setItems((prev) =>
        prev.map((item) => item.id === id ? { ...item, is_favorite: current } : item)
      );
      toast.error("Gagal mengubah favorit");
    }
  };

  const handleDelete = async (id: string) => {
    setItems((prev) => prev.filter((item) => item.id !== id));
    try {
      const res = await fetch(`/api/history?id=${id}&type=ugc`, { method: "DELETE" });
      if (!res.ok) throw new Error();
      toast.success("Riwayat dihapus");
    } catch {
      toast.error("Gagal menghapus riwayat");
      fetchUGCHistory(); // re-fetch to restore state
    }
  };

  const filtered = items.filter((item) => {
    if (!search) return true;
    return (item.product_name ?? "").toLowerCase().includes(search.toLowerCase());
  });

  return (
    <div className="space-y-4">
      {/* Search */}
      <div className="relative">
        <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 riwayat UGC..."
          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>

      {loading ? (
        <div className="space-y-3">
          {[1, 2, 3].map((i) => (
            <div key={i} className="h-20 rounded-xl bg-card border border-border animate-pulse" />
          ))}
        </div>
      ) : filtered.length === 0 ? (
        <div className="text-center py-16 text-muted-foreground">
          <Film className="w-12 h-12 mx-auto mb-3 opacity-30" />
          <p className="font-medium">Belum ada riwayat UGC</p>
          <p className="text-sm mt-1">Gunakan Generator UGC untuk membuat script produk pertamamu!</p>
        </div>
      ) : (
        <div className="space-y-3">
          {filtered.map((item) => (
            <UGCHistoryCard
              key={item.id}
              item={item}
              onToggleFavorite={handleToggleFavorite}
              onDelete={handleDelete}
            />
          ))}
        </div>
      )}
    </div>
  );
}
