"use client";

import { useState } from "react";
import {
  Copy, CheckCircle2, Download, ChevronDown, ChevronUp,
  Zap, Film, MessageSquare, Hash, Megaphone, Lightbulb, RotateCcw,
} from "lucide-react";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import type { UGCPackage } from "@/types/ugc-generator";
import { UGC_PLATFORMS } from "@/types/ugc-generator";

// ─── Copy button kecil ────────────────────────────────────────────────────────
function CopyBtn({ text, label = "Salin" }: { text: string; label?: string }) {
  const [copied, setCopied] = useState(false);
  const handle = async () => {
    await navigator.clipboard.writeText(text);
    setCopied(true);
    toast.success(`${label} disalin!`);
    setTimeout(() => setCopied(false), 2000);
  };
  return (
    <button
      type="button"
      onClick={handle}
      className={cn(
        "flex items-center gap-1 text-xs px-2.5 py-1.5 rounded-lg border transition-all",
        copied
          ? "border-emerald-500/30 bg-emerald-500/10 text-emerald-400"
          : "border-border bg-accent/60 text-muted-foreground hover:text-foreground hover:border-primary/40"
      )}
    >
      {copied ? <CheckCircle2 className="w-3.5 h-3.5" /> : <Copy className="w-3.5 h-3.5" />}
      {copied ? "Disalin!" : label}
    </button>
  );
}

// ─── Section card ─────────────────────────────────────────────────────────────
function Section({
  icon, title, accent = "violet", children, defaultOpen = true,
}: {
  icon: React.ReactNode;
  title: string;
  accent?: string;
  children: React.ReactNode;
  defaultOpen?: boolean;
}) {
  const [open, setOpen] = useState(defaultOpen);
  const colors: Record<string, string> = {
    violet: "from-violet-600 to-blue-600",
    rose:   "from-rose-600 to-orange-600",
    amber:  "from-amber-500 to-yellow-600",
    cyan:   "from-cyan-600 to-teal-600",
    green:  "from-green-600 to-emerald-600",
    pink:   "from-pink-600 to-purple-600",
  };
  return (
    <div className="glass-card rounded-xl overflow-hidden border border-border/40">
      <button
        type="button"
        onClick={() => setOpen(!open)}
        className="w-full flex items-center gap-3 p-3.5 hover:bg-white/3 transition-colors text-left"
      >
        <div className={cn("w-7 h-7 rounded-lg bg-gradient-to-br flex items-center justify-center flex-shrink-0", colors[accent] ?? colors.violet)}>
          <span className="text-white w-3.5 h-3.5 flex items-center justify-center">{icon}</span>
        </div>
        <span className="text-sm font-semibold flex-1">{title}</span>
        {open ? <ChevronUp className="w-4 h-4 text-muted-foreground" /> : <ChevronDown className="w-4 h-4 text-muted-foreground" />}
      </button>
      {open && <div className="px-4 pb-4 border-t border-border/30">{children}</div>}
    </div>
  );
}

// ─── Main Output ──────────────────────────────────────────────────────────────
interface Props {
  output: UGCPackage;
  onReset: () => void;
}

export default function UGCOutput({ output, onReset }: Props) {
  const platformInfo = UGC_PLATFORMS[output.metadata.platform];

  // Build full download text
  const buildDownloadText = () => [
    `UGC PACKAGE — ${output.metadata.platform.toUpperCase()}`,
    `Platform : ${platformInfo?.label ?? output.metadata.platform}`,
    `Durasi   : ${output.metadata.durasi}`,
    `Dibuat   : ${new Date(output.metadata.generatedAt).toLocaleString("id-ID")}`,
    "",
    "═══════════════════════════════════",
    "🪝 HOOK PEMBUKA",
    "═══════════════════════════════════",
    output.hook,
    "",
    "═══════════════════════════════════",
    "🎬 SCRIPT BREAKDOWN",
    "═══════════════════════════════════",
    ...output.script.flatMap((s) => [
      `[${s.durasi}]`,
      `Aksi   : ${s.aksi}`,
      `Dialog : ${s.dialog}`,
      `Visual : ${s.visualNote}`,
      "",
    ]),
    "═══════════════════════════════════",
    "📜 FULL SCRIPT",
    "═══════════════════════════════════",
    output.fullScript,
    "",
    "═══════════════════════════════════",
    "📣 CALL TO ACTION",
    "═══════════════════════════════════",
    output.callToAction,
    "",
    "═══════════════════════════════════",
    "💬 CAPTION",
    "═══════════════════════════════════",
    output.caption,
    "",
    "═══════════════════════════════════",
    "# HASHTAGS",
    "═══════════════════════════════════",
    output.hashtags.join(" "),
    "",
    "═══════════════════════════════════",
    "💡 TIPS PRODUKSI",
    "═══════════════════════════════════",
    ...output.tipsProduction.map((t, i) => `${i + 1}. ${t}`),
  ].join("\n");

  const handleDownload = () => {
    const blob = new Blob([buildDownloadText()], { type: "text/plain" });
    const a    = document.createElement("a");
    a.href     = URL.createObjectURL(blob);
    a.download = `ugc-package-${Date.now()}.txt`;
    a.click();
    toast.success("UGC Package didownload!");
  };

  return (
    <div className="space-y-3">
      {/* ── Header ── */}
      <div className="glass-card rounded-xl p-4 bg-gradient-to-r from-violet-500/10 via-purple-500/10 to-blue-500/10 border border-violet-500/20">
        <div className="flex items-center gap-3">
          <span className="text-2xl">{platformInfo?.icon ?? "🎬"}</span>
          <div className="flex-1 min-w-0">
            <p className="text-sm font-bold">UGC Package Siap! ✨</p>
            <p className="text-xs text-muted-foreground mt-0.5">
              {platformInfo?.label ?? output.metadata.platform} · {output.metadata.durasi} · {output.script.length} scene
            </p>
          </div>
          <div className="flex gap-2 flex-shrink-0">
            <button
              type="button"
              onClick={onReset}
              title="Buat ulang"
              className="p-2 rounded-lg border border-border text-muted-foreground hover:text-foreground hover:border-primary/40 transition-colors"
            >
              <RotateCcw className="w-4 h-4" />
            </button>
            <button
              type="button"
              onClick={handleDownload}
              className="flex items-center gap-1.5 px-3 py-2 rounded-lg border border-primary/40 bg-primary/10 text-primary text-xs font-medium hover:bg-primary/20 transition-colors"
            >
              <Download className="w-3.5 h-3.5" />
              Download
            </button>
          </div>
        </div>
      </div>

      {/* ── Hook ── */}
      <Section icon={<Zap />} title="🪝 Hook Pembuka" accent="rose">
        <div className="pt-3 rounded-xl bg-gradient-to-r from-rose-500/10 to-orange-500/10 border border-rose-500/20 p-3">
          <p className="text-sm font-semibold italic leading-relaxed">"{output.hook}"</p>
        </div>
        <div className="flex justify-end mt-2">
          <CopyBtn text={output.hook} label="Salin Hook" />
        </div>
      </Section>

      {/* ── Script Breakdown ── */}
      <Section icon={<Film />} title={`🎬 Script Breakdown (${output.script.length} scene)`} accent="violet">
        <div className="pt-3 space-y-3">
          {output.script.map((scene, i) => (
            <div key={i} className="rounded-xl border border-border/40 bg-accent/30 overflow-hidden">
              <div className="flex items-center gap-2 px-3 py-2 border-b border-border/30 bg-accent/40">
                <div className="w-6 h-6 rounded-md bg-gradient-to-br from-violet-600 to-blue-600 flex items-center justify-center flex-shrink-0">
                  <span className="text-white text-[10px] font-bold">{i + 1}</span>
                </div>
                <span className="text-xs font-semibold text-violet-300">{scene.durasi}</span>
              </div>
              <div className="p-3 space-y-2">
                {/* Aksi */}
                <div>
                  <p className="text-[10px] text-muted-foreground mb-0.5 uppercase tracking-wide">📹 Aksi</p>
                  <p className="text-xs text-foreground/80">{scene.aksi}</p>
                </div>
                {/* Dialog */}
                <div className="bg-violet-500/8 rounded-lg px-2.5 py-2 border border-violet-500/15">
                  <p className="text-[10px] text-violet-300 mb-0.5 uppercase tracking-wide">🎙️ Dialog</p>
                  <p className="text-xs italic">"{scene.dialog}"</p>
                </div>
                {/* Visual */}
                <div>
                  <p className="text-[10px] text-muted-foreground mb-0.5 uppercase tracking-wide">🎞️ Visual</p>
                  <p className="text-xs text-foreground/70">{scene.visualNote}</p>
                </div>
              </div>
            </div>
          ))}
        </div>
      </Section>

      {/* ── Full Script ── */}
      <Section icon={<MessageSquare />} title="📜 Full Script" accent="cyan" defaultOpen={false}>
        <div className="pt-3">
          <div className="bg-accent/60 rounded-xl p-3 border border-border/40">
            <p className="text-sm leading-relaxed whitespace-pre-wrap">{output.fullScript}</p>
          </div>
          <div className="flex justify-end mt-2">
            <CopyBtn text={output.fullScript} label="Salin Full Script" />
          </div>
        </div>
      </Section>

      {/* ── CTA ── */}
      <Section icon={<Megaphone />} title="📣 Call to Action" accent="amber">
        <div className="pt-3 bg-amber-500/8 rounded-xl p-3 border border-amber-500/20">
          <p className="text-sm font-medium">{output.callToAction}</p>
        </div>
        <div className="flex justify-end mt-2">
          <CopyBtn text={output.callToAction} label="Salin CTA" />
        </div>
      </Section>

      {/* ── Caption ── */}
      <Section icon={<MessageSquare />} title="💬 Caption" accent="pink" defaultOpen={false}>
        <div className="pt-3">
          <div className="bg-accent/60 rounded-xl p-3 border border-border/40">
            <p className="text-sm leading-relaxed whitespace-pre-wrap">{output.caption}</p>
          </div>
          <div className="flex justify-end mt-2">
            <CopyBtn text={output.caption} label="Salin Caption" />
          </div>
        </div>
      </Section>

      {/* ── Hashtags ── */}
      <Section icon={<Hash />} title="# Hashtags" accent="green" defaultOpen={false}>
        <div className="pt-3">
          <div className="flex flex-wrap gap-1.5">
            {output.hashtags.map((tag, i) => (
              <span
                key={i}
                className="text-xs px-2.5 py-1 rounded-full bg-green-500/10 text-green-300 border border-green-500/20 cursor-pointer hover:bg-green-500/20 transition-colors"
                onClick={() => { navigator.clipboard.writeText(tag); toast.success(`${tag} disalin!`); }}
              >
                {tag.startsWith("#") ? tag : `#${tag}`}
              </span>
            ))}
          </div>
          <div className="flex justify-end mt-3">
            <CopyBtn text={output.hashtags.map((t) => t.startsWith("#") ? t : `#${t}`).join(" ")} label="Salin Semua Hashtag" />
          </div>
        </div>
      </Section>

      {/* ── Tips Produksi ── */}
      {output.tipsProduction.length > 0 && (
        <Section icon={<Lightbulb />} title="💡 Tips Produksi" accent="amber" defaultOpen={false}>
          <div className="pt-3 space-y-2">
            {output.tipsProduction.map((tip, i) => (
              <div key={i} className="flex items-start gap-2.5">
                <span className="w-5 h-5 rounded-full bg-amber-500/15 text-amber-400 text-[10px] font-bold flex items-center justify-center flex-shrink-0 mt-0.5">
                  {i + 1}
                </span>
                <p className="text-sm text-foreground/80 leading-relaxed">{tip}</p>
              </div>
            ))}
          </div>
        </Section>
      )}

      {/* ── Footer ── */}
      <p className="text-center text-[10px] text-muted-foreground">
        Generated by {output.metadata.model} · {new Date(output.metadata.generatedAt).toLocaleString("id-ID")}
      </p>
    </div>
  );
}
