"use client";

import { useState } from "react";
import {
  ImageIcon, Wand2, Loader2, Copy, CheckCircle2,
  ChevronDown, Settings2, Sparkles, Info,
} from "lucide-react";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import type {
  StoryboardOutput,
  GptImagePromptsOutput,
  GptImageScenePrompt,
  GptImageAspectRatio,
  GptImageQuality,
} from "@/types/storyboard";

// ── Aspect ratio options ────────────────────────────────────────────────────
const ASPECT_RATIO_OPTIONS: { value: GptImageAspectRatio; label: string; desc: string; icon: string }[] = [
  { value: "16:9",  label: "16:9",  desc: "Landscape · YouTube",       icon: "🖥️" },
  { value: "9:16",  label: "9:16",  desc: "Portrait · Reels / TikTok", icon: "📱" },
  { value: "1:1",   label: "1:1",   desc: "Square · Instagram",        icon: "⬜" },
  { value: "4:3",   label: "4:3",   desc: "Standard",                  icon: "📺" },
  { value: "3:4",   label: "3:4",   desc: "Portrait · Pinterest",      icon: "📌" },
];

const QUALITY_OPTIONS: { value: GptImageQuality; label: string; desc: string }[] = [
  { value: "hd",       label: "HD",       desc: "Lebih detail, sedikit lebih lambat" },
  { value: "standard", label: "Standard", desc: "Lebih cepat, tetap bagus" },
];

// ── Single scene prompt card ────────────────────────────────────────────────
function ScenePromptCard({
  sp,
  index,
}: {
  sp: GptImageScenePrompt;
  index: number;
}) {
  const [copied, setCopied] = useState(false);
  const [showDetails, setShowDetails] = useState(false);

  const handleCopy = async () => {
    await navigator.clipboard.writeText(sp.prompt);
    setCopied(true);
    toast.success(`Prompt Scene ${sp.sceneNumber} disalin!`);
    setTimeout(() => setCopied(false), 2000);
  };

  return (
    <div className="glass-card rounded-xl border border-border/40 overflow-hidden">
      {/* ── Header ── */}
      <div className="flex items-center gap-3 p-3 bg-accent/30">
        {/* Scene number badge */}
        <div className="w-7 h-7 rounded-lg bg-gradient-to-br from-rose-500 to-orange-500 flex items-center justify-center flex-shrink-0 shadow shadow-rose-500/30">
          <span className="text-white text-xs font-bold">{sp.sceneNumber}</span>
        </div>
        <div className="flex-1 min-w-0">
          <p className="text-xs font-semibold truncate">{sp.title}</p>
          <p className="text-[10px] text-muted-foreground">{sp.colorMood}</p>
        </div>
        {/* Aspect ratio badge */}
        <span className="flex-shrink-0 text-[10px] px-2 py-0.5 rounded-full bg-primary/10 text-primary border border-primary/20 font-medium">
          {sp.aspectRatio}
        </span>
      </div>

      {/* ── Prompt text ── */}
      <div className="p-3 space-y-2">
        <p className="text-xs leading-relaxed text-foreground/90 line-clamp-4">{sp.prompt}</p>

        {/* Composition note */}
        {sp.compositionNote && (
          <div className="flex items-start gap-1.5 text-[10px] text-muted-foreground">
            <Info className="w-3 h-3 flex-shrink-0 mt-0.5" />
            <span>{sp.compositionNote}</span>
          </div>
        )}
      </div>

      {/* ── Expand / Negative hint ── */}
      {sp.negativeHint && (
        <div className="px-3 pb-2">
          <button
            type="button"
            onClick={() => setShowDetails(!showDetails)}
            className="text-[10px] text-muted-foreground hover:text-foreground flex items-center gap-1 transition-colors"
          >
            <ChevronDown className={cn("w-3 h-3 transition-transform", showDetails && "rotate-180")} />
            {showDetails ? "Sembunyikan" : "Lihat negative hint"}
          </button>
          {showDetails && (
            <p className="mt-1.5 text-[10px] text-rose-300/80 bg-rose-500/5 rounded-lg px-2 py-1.5 leading-relaxed border border-rose-500/10">
              ⚠️ Hindari: {sp.negativeHint}
            </p>
          )}
        </div>
      )}

      {/* ── Copy button ── */}
      <div className="px-3 pb-3">
        <button
          type="button"
          onClick={handleCopy}
          className={cn(
            "w-full py-2 rounded-lg text-xs font-medium flex items-center justify-center gap-1.5 transition-all border",
            copied
              ? "bg-emerald-500/10 text-emerald-400 border-emerald-500/30"
              : "bg-accent/60 text-muted-foreground hover:text-foreground hover:bg-accent border-border hover:border-primary/40"
          )}
        >
          {copied ? (
            <><CheckCircle2 className="w-3.5 h-3.5" /> Disalin!</>
          ) : (
            <><Copy className="w-3.5 h-3.5" /> Salin Prompt</>
          )}
        </button>
      </div>
    </div>
  );
}

// ── Copy all prompts ────────────────────────────────────────────────────────
function buildAllPromptsText(output: GptImagePromptsOutput): string {
  return output.scenePrompts
    .map(
      (sp) =>
        `=== Scene ${sp.sceneNumber}: ${sp.title} ===\n` +
        `Aspect: ${sp.aspectRatio} | Quality: ${sp.quality}\n` +
        `Composition: ${sp.compositionNote}\n` +
        `Color & Mood: ${sp.colorMood}\n\n` +
        `PROMPT:\n${sp.prompt}\n\n` +
        `Negative hint: ${sp.negativeHint}`
    )
    .join("\n\n" + "─".repeat(50) + "\n\n");
}

// ── Main component ──────────────────────────────────────────────────────────
interface Props {
  storyboard: StoryboardOutput;
}

export default function StoryboardImageGrid({ storyboard }: Props) {
  const [aspectRatio, setAspectRatio]   = useState<GptImageAspectRatio>("16:9");
  const [quality, setQuality]           = useState<GptImageQuality>("hd");
  const [showSettings, setShowSettings] = useState(false);
  const [loading, setLoading]           = useState(false);
  const [output, setOutput]             = useState<GptImagePromptsOutput | null>(null);
  const [copiedAll, setCopiedAll]       = useState(false);

  const handleGenerate = async () => {
    setLoading(true);
    setOutput(null);
    try {
      const res = await fetch("/api/storyboard/gptimage-prompts", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          scenes:       storyboard.scenes,
          style:        storyboard.metadata.style,
          language:     "id",
          aspectRatio,
          quality,
          extraContext: `${storyboard.theme}. Hook: ${storyboard.hook}`,
        }),
      });

      const data = await res.json();

      if (!data.success) {
        if (data.redirectTo) {
          toast.error(data.error);
          setTimeout(() => (window.location.href = data.redirectTo), 2000);
          return;
        }
        toast.error(data.error ?? "Gagal generate prompts");
        return;
      }

      setOutput(data.data as GptImagePromptsOutput);
      toast.success(`${(data.data as GptImagePromptsOutput).scenePrompts.length} prompt GPT Image siap! 🎨`);
    } catch {
      toast.error("Terjadi kesalahan. Periksa koneksi internet kamu.");
    } finally {
      setLoading(false);
    }
  };

  const handleCopyAll = async () => {
    if (!output) return;
    await navigator.clipboard.writeText(buildAllPromptsText(output));
    setCopiedAll(true);
    toast.success("Semua prompt disalin!");
    setTimeout(() => setCopiedAll(false), 2500);
  };

  return (
    <div className="space-y-4">

      {/* ── Settings panel ── */}
      <div className="glass-card rounded-xl overflow-hidden">
        <button
          type="button"
          onClick={() => setShowSettings(!showSettings)}
          className="w-full flex items-center justify-between px-4 py-3 hover:bg-white/3 transition-colors"
        >
          <div className="flex items-center gap-2 text-sm font-medium">
            <Settings2 className="w-4 h-4 text-rose-400" />
            Pengaturan GPT Image
            <span className="text-xs text-muted-foreground font-normal">
              {aspectRatio} · {quality === "hd" ? "HD" : "Standard"}
            </span>
          </div>
          <ChevronDown className={cn("w-4 h-4 text-muted-foreground transition-transform", showSettings && "rotate-180")} />
        </button>

        {showSettings && (
          <div className="px-4 pb-4 space-y-4 border-t border-border/40 pt-4">
            {/* Aspect ratio */}
            <div className="space-y-2">
              <label className="text-xs font-medium text-muted-foreground">Aspect Ratio</label>
              <div className="grid grid-cols-5 gap-1.5">
                {ASPECT_RATIO_OPTIONS.map((opt) => (
                  <button
                    key={opt.value}
                    type="button"
                    onClick={() => setAspectRatio(opt.value)}
                    className={cn(
                      "flex flex-col items-center gap-1 py-2 px-1 rounded-lg border text-center transition-all",
                      aspectRatio === opt.value
                        ? "border-rose-500 bg-rose-500/10 text-rose-300"
                        : "border-border bg-accent/50 text-muted-foreground hover:border-rose-500/40 hover:text-foreground"
                    )}
                  >
                    <span className="text-base">{opt.icon}</span>
                    <span className="text-[10px] font-semibold">{opt.label}</span>
                    <span className="text-[9px] leading-tight hidden sm:block">{opt.desc.split(" · ")[0]}</span>
                  </button>
                ))}
              </div>
              <p className="text-[10px] text-muted-foreground">
                {ASPECT_RATIO_OPTIONS.find((o) => o.value === aspectRatio)?.desc}
              </p>
            </div>

            {/* Quality */}
            <div className="space-y-2">
              <label className="text-xs font-medium text-muted-foreground">Kualitas</label>
              <div className="flex gap-2">
                {QUALITY_OPTIONS.map((opt) => (
                  <button
                    key={opt.value}
                    type="button"
                    onClick={() => setQuality(opt.value)}
                    className={cn(
                      "flex-1 py-2.5 px-3 rounded-lg border text-xs font-medium transition-all text-left",
                      quality === opt.value
                        ? "border-orange-500 bg-orange-500/10 text-orange-300"
                        : "border-border bg-accent/50 text-muted-foreground hover:border-orange-500/40 hover:text-foreground"
                    )}
                  >
                    <div className="font-semibold">{opt.label}</div>
                    <div className="text-[10px] opacity-70 mt-0.5">{opt.desc}</div>
                  </button>
                ))}
              </div>
            </div>
          </div>
        )}
      </div>

      {/* ── Storyboard summary ── */}
      <div className="rounded-xl bg-gradient-to-r from-rose-500/10 via-orange-500/10 to-amber-500/10 border border-rose-500/20 p-3">
        <div className="flex items-start gap-2">
          <ImageIcon className="w-4 h-4 text-rose-400 flex-shrink-0 mt-0.5" />
          <div className="flex-1 min-w-0">
            <p className="text-xs font-semibold text-rose-300">
              GPT Image Prompts — {storyboard.scenes.length} scene
            </p>
            <p className="text-[10px] text-muted-foreground mt-0.5 line-clamp-2">
              Generate satu prompt gambar per scene, siap dipakai langsung di GPT Image (DALL-E 3 / gpt-image-2).
            </p>
          </div>
        </div>
      </div>

      {/* ── Generate button ── */}
      {!output && (
        <button
          type="button"
          onClick={handleGenerate}
          disabled={loading}
          className="w-full py-3.5 rounded-xl bg-gradient-to-r from-rose-600 via-orange-600 to-amber-600 text-white font-semibold hover:opacity-90 transition-all disabled:opacity-50 flex items-center justify-center gap-2 shadow-lg shadow-rose-500/25"
        >
          {loading ? (
            <><Loader2 className="w-4 h-4 animate-spin" />Generating {storyboard.scenes.length} prompt gambar...</>
          ) : (
            <><Sparkles className="w-4 h-4" />Generate GPT Image Prompts ({storyboard.scenes.length} scene)</>
          )}
        </button>
      )}

      {loading && (
        <p className="text-center text-xs text-muted-foreground">
          AI sedang membuat prompt gambar untuk setiap scene… (~10-20 detik)
        </p>
      )}

      {/* ── Output grid ── */}
      {output && (
        <div className="space-y-4">
          {/* Toolbar */}
          <div className="flex items-center justify-between">
            <div className="text-xs text-muted-foreground flex items-center gap-1.5">
              <Sparkles className="w-3.5 h-3.5 text-amber-400" />
              <span className="font-medium text-foreground">{output.scenePrompts.length}</span> prompt siap
              <span>·</span>
              <span>{output.metadata.aspectRatio}</span>
              <span>·</span>
              <span>{output.metadata.quality === "hd" ? "HD" : "Standard"}</span>
            </div>
            <div className="flex gap-2">
              {/* Regenerate */}
              <button
                type="button"
                onClick={handleGenerate}
                disabled={loading}
                className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-border text-xs text-muted-foreground hover:text-foreground hover:border-primary/40 transition-colors disabled:opacity-50"
              >
                <Wand2 className="w-3.5 h-3.5" />
                Regenerate
              </button>
              {/* Copy all */}
              <button
                type="button"
                onClick={handleCopyAll}
                className={cn(
                  "flex items-center gap-1.5 px-3 py-1.5 rounded-lg border text-xs font-medium transition-all",
                  copiedAll
                    ? "border-emerald-500/40 bg-emerald-500/10 text-emerald-400"
                    : "border-primary/40 bg-primary/10 text-primary hover:bg-primary/20"
                )}
              >
                {copiedAll ? (
                  <><CheckCircle2 className="w-3.5 h-3.5" />Semua disalin!</>
                ) : (
                  <><Copy className="w-3.5 h-3.5" />Salin Semua</>
                )}
              </button>
            </div>
          </div>

          {/* Grid */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
            {output.scenePrompts.map((sp, i) => (
              <ScenePromptCard key={sp.sceneNumber} sp={sp} index={i} />
            ))}
          </div>

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