"use client";

import { useState } from "react";
import {
  Copy, Download, ExternalLink, Film, Sparkles,
  ChevronDown, ChevronUp, Clock, Camera, Zap,
  Globe, Facebook, Instagram, Twitter, RotateCcw, ImageIcon,
} from "lucide-react";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import type { StoryboardOutput, StoryboardScene } from "@/types/storyboard";
import { STORYBOARD_STYLES } from "@/types/storyboard";
import StoryboardImageGrid from "./StoryboardImageGrid";
import SceneToGeneratorButton from "./SceneToGeneratorButton";

interface Props {
  output: StoryboardOutput;
  onReset: () => void;
}

// Platform icon helper
function PlatformIcon({ platform }: { platform: string }) {
  switch (platform) {
    case "facebook":  return <Facebook className="w-3.5 h-3.5 text-blue-400" />;
    case "instagram": return <Instagram className="w-3.5 h-3.5 text-pink-400" />;
    case "twitter":   return <Twitter className="w-3.5 h-3.5 text-sky-400" />;
    default:          return <Globe className="w-3.5 h-3.5 text-green-400" />;
  }
}

// Single scene card
function SceneCard({
  scene,
  index,
  storyboardStyle,
}: {
  scene: StoryboardScene;
  index: number;
  storyboardStyle: string;
}) {
  const [expanded, setExpanded] = useState(index < 3); // first 3 expanded by default

  return (
    <div className="glass-card rounded-xl border border-border/40 overflow-hidden transition-all">
      {/* Scene header */}
      <button
        type="button"
        onClick={() => setExpanded(!expanded)}
        className="w-full flex items-center gap-3 p-4 hover:bg-white/3 transition-colors text-left"
      >
        {/* Scene number badge */}
        <div className="w-8 h-8 rounded-lg bg-gradient-to-br from-violet-600 to-blue-600 flex items-center justify-center flex-shrink-0 shadow shadow-violet-500/30">
          <span className="text-white text-xs font-bold">{scene.sceneNumber}</span>
        </div>

        <div className="flex-1 min-w-0">
          <div className="font-medium text-sm truncate">{scene.title}</div>
          {!expanded && (
            <div className="text-xs text-muted-foreground truncate mt-0.5">{scene.narration}</div>
          )}
        </div>

        <div className="flex items-center gap-2 flex-shrink-0">
          {scene.duration && (
            <span className="text-xs text-muted-foreground flex items-center gap-1">
              <Clock className="w-3 h-3" /> {scene.duration}
            </span>
          )}
          {expanded ? <ChevronUp className="w-4 h-4 text-muted-foreground" /> : <ChevronDown className="w-4 h-4 text-muted-foreground" />}
        </div>
      </button>

      {/* Scene details */}
      {expanded && (
        <div className="px-4 pb-4 space-y-3 border-t border-border/30">
          {/* Narration */}
          <div className="pt-3">
            <div className="text-xs text-muted-foreground mb-1.5 flex items-center gap-1">
              <Zap className="w-3 h-3" /> Narasi / Caption
            </div>
            <p className="text-sm leading-relaxed bg-accent/50 rounded-lg p-3 italic">
              "{scene.narration}"
            </p>
          </div>

          {/* Visual description */}
          <div>
            <div className="text-xs text-muted-foreground mb-1.5 flex items-center gap-1">
              <Camera className="w-3 h-3" /> Deskripsi Visual
            </div>
            <p className="text-sm leading-relaxed text-foreground/80">{scene.visualDescription}</p>
          </div>

          {/* Meta row + Generate button */}
          <div className="flex flex-wrap items-center gap-2">
            {scene.cameraAngle && (
              <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full bg-violet-500/10 text-violet-300 text-xs">
                📷 {scene.cameraAngle}
              </span>
            )}
            {scene.emotion && (
              <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full bg-rose-500/10 text-rose-300 text-xs">
                💭 {scene.emotion}
              </span>
            )}
            {scene.transition && (
              <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full bg-cyan-500/10 text-cyan-300 text-xs">
                → {scene.transition}
              </span>
            )}
            {/* ── Pipeline button ── */}
            <div className="ml-auto">
              <SceneToGeneratorButton
                scene={scene}
                storyboardStyle={storyboardStyle}
              />
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// Main output component
export default function StoryboardOutput({ output, onReset }: Props) {
  const [activeTab, setActiveTab] = useState<"scenes" | "summary" | "gptimage" | "json">("scenes");

  const styleInfo = STORYBOARD_STYLES[output.metadata.style];

  // Copy handler
  const copyText = (text: string, label: string) => {
    navigator.clipboard.writeText(text).then(() => toast.success(`${label} disalin!`));
  };

  // Download as TXT
  const downloadTxt = () => {
    const lines: string[] = [
      `STORYBOARD: ${output.sourceTitle}`,
      `Sumber: ${output.sourceUrl}`,
      `Style: ${styleInfo?.label ?? output.metadata.style}`,
      `Dibuat: ${new Date(output.metadata.generatedAt).toLocaleString("id-ID")}`,
      `Estimasi durasi: ${output.metadata.estimatedDuration}`,
      "",
      "═══════════════════════════",
      "TEMA UTAMA",
      "═══════════════════════════",
      output.theme,
      "",
      "═══════════════════════════",
      "HOOK PEMBUKA",
      "═══════════════════════════",
      output.hook,
      "",
      "═══════════════════════════",
      "RINGKASAN CERITA",
      "═══════════════════════════",
      output.summary,
      "",
      "═══════════════════════════",
      `SCENE LIST (${output.scenes.length} scenes)`,
      "═══════════════════════════",
      ...output.scenes.flatMap((s) => [
        "",
        `SCENE ${s.sceneNumber}: ${s.title}`,
        `Durasi: ${s.duration}`,
        `Narasi: ${s.narration}`,
        `Visual: ${s.visualDescription}`,
        s.cameraAngle ? `Kamera: ${s.cameraAngle}` : "",
        s.emotion ? `Emosi: ${s.emotion}` : "",
        s.transition ? `Transisi: ${s.transition}` : "",
      ].filter(Boolean)),
      "",
      "═══════════════════════════",
      "CALL TO ACTION",
      "═══════════════════════════",
      output.callToAction,
    ];

    const blob = new Blob([lines.join("\n")], { type: "text/plain" });
    const a = document.createElement("a");
    a.href = URL.createObjectURL(blob);
    a.download = `storyboard-${Date.now()}.txt`;
    a.click();
    toast.success("Storyboard didownload!");
  };

  // Download as JSON
  const downloadJson = () => {
    const blob = new Blob([JSON.stringify(output, null, 2)], { type: "application/json" });
    const a = document.createElement("a");
    a.href = URL.createObjectURL(blob);
    a.download = `storyboard-${Date.now()}.json`;
    a.click();
    toast.success("JSON didownload!");
  };

  return (
    <div className="space-y-4">
      {/* ── Header card ── */}
      <div className="glass-card rounded-xl p-4 space-y-3">
        {/* Source info */}
        <div className="flex items-start gap-2">
          <PlatformIcon platform={output.sourcePlatform} />
          <div className="flex-1 min-w-0">
            <p className="text-xs text-muted-foreground">Sumber konten</p>
            <p className="text-sm font-medium truncate">{output.sourceTitle}</p>
            <a
              href={output.sourceUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="text-xs text-primary flex items-center gap-1 mt-0.5 hover:underline truncate"
            >
              <ExternalLink className="w-3 h-3 flex-shrink-0" />
              {output.sourceUrl}
            </a>
          </div>
        </div>

        {/* Meta badges */}
        <div className="flex flex-wrap gap-2">
          <span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full bg-violet-500/15 text-violet-300 text-xs font-medium">
            {styleInfo?.icon} {styleInfo?.label ?? output.metadata.style}
          </span>
          <span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full bg-blue-500/10 text-blue-300 text-xs">
            <Film className="w-3 h-3" /> {output.metadata.totalScenes} scenes
          </span>
          <span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full bg-cyan-500/10 text-cyan-300 text-xs" title="Durasi per scene">
            ⏱ {output.metadata.sceneDuration}/scene
          </span>
          <span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full bg-emerald-500/10 text-emerald-300 text-xs" title="Total durasi video">
            <Clock className="w-3 h-3" /> {output.metadata.totalDuration}
          </span>
          <span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full bg-amber-500/10 text-amber-300 text-xs">
            <Sparkles className="w-3 h-3" /> {output.metadata.model.split("/")[0]}
          </span>
        </div>

        {/* Theme + Hook */}
        <div className="space-y-2">
          <div className="rounded-lg bg-accent/60 p-3">
            <p className="text-xs text-muted-foreground mb-1">🎯 Tema Utama</p>
            <p className="text-sm font-medium">{output.theme}</p>
          </div>
          <div className="rounded-lg bg-gradient-to-r from-violet-500/10 to-blue-500/10 border border-violet-500/20 p-3">
            <p className="text-xs text-muted-foreground mb-1">🪝 Hook Pembuka</p>
            <p className="text-sm italic">"{output.hook}"</p>
            <button
              type="button"
              onClick={() => copyText(output.hook, "Hook")}
              className="mt-2 text-xs text-muted-foreground hover:text-foreground flex items-center gap-1 transition-colors"
            >
              <Copy className="w-3 h-3" /> Salin hook
            </button>
          </div>
        </div>
      </div>

      {/* ── Tabs ── */}
      <div className="glass-card rounded-xl p-1 flex gap-1 flex-wrap">
        {([
          { key: "scenes",   label: `🎬 Scene (${output.scenes.length})` },
          { key: "gptimage", label: "🎨 GPT Image" },
          { key: "summary",  label: "📝 Ringkasan" },
          { key: "json",     label: "{ } JSON" },
        ] as const).map((tab) => (
          <button
            key={tab.key}
            type="button"
            onClick={() => setActiveTab(tab.key)}
            className={cn(
              "flex-1 py-2 px-2 rounded-lg text-xs font-medium transition-colors whitespace-nowrap min-w-0",
              activeTab === tab.key
                ? tab.key === "gptimage"
                  ? "bg-gradient-to-r from-rose-600 to-orange-600 text-white"
                  : "bg-primary text-primary-foreground"
                : "text-muted-foreground hover:text-foreground"
            )}
          >
            {tab.label}
          </button>
        ))}
      </div>

      {/* ── Tab: Scenes ── */}
      {activeTab === "scenes" && (
        <div className="space-y-2">
          {output.scenes.map((scene, i) => (
            <SceneCard
              key={scene.sceneNumber}
              scene={scene}
              index={i}
              storyboardStyle={output.metadata.style}
            />
          ))}

          {/* CTA */}
          {output.callToAction && (
            <div className="glass-card rounded-xl p-4 border border-amber-500/20 bg-amber-500/5">
              <p className="text-xs text-amber-400 mb-1 font-medium">📣 Call to Action</p>
              <p className="text-sm">{output.callToAction}</p>
              <button
                type="button"
                onClick={() => copyText(output.callToAction, "CTA")}
                className="mt-2 text-xs text-muted-foreground hover:text-foreground flex items-center gap-1"
              >
                <Copy className="w-3 h-3" /> Salin CTA
              </button>
            </div>
          )}
        </div>
      )}

      {/* ── Tab: GPT Image ── */}
      {activeTab === "gptimage" && (
        <StoryboardImageGrid storyboard={output} />
      )}

      {/* ── Tab: Summary ── */}
      {activeTab === "summary" && (
        <div className="glass-card rounded-xl p-4 space-y-3">
          <div className="flex items-center justify-between">
            <h3 className="text-sm font-medium">Ringkasan Cerita</h3>
            <button
              type="button"
              onClick={() => copyText(output.summary, "Ringkasan")}
              className="text-xs text-muted-foreground hover:text-foreground flex items-center gap-1"
            >
              <Copy className="w-3 h-3" /> Salin
            </button>
          </div>
          <div className="text-sm leading-relaxed text-foreground/85 whitespace-pre-wrap">
            {output.summary}
          </div>
        </div>
      )}

      {/* ── Tab: JSON ── */}
      {activeTab === "json" && (
        <div className="glass-card rounded-xl p-4 space-y-2">
          <div className="flex items-center justify-between">
            <h3 className="text-sm font-medium">Raw JSON Output</h3>
            <button
              type="button"
              onClick={() => copyText(JSON.stringify(output, null, 2), "JSON")}
              className="text-xs text-muted-foreground hover:text-foreground flex items-center gap-1"
            >
              <Copy className="w-3 h-3" /> Salin
            </button>
          </div>
          <pre className="text-xs bg-accent/80 rounded-lg p-3 overflow-x-auto max-h-96 overflow-y-auto text-green-300/80">
            {JSON.stringify(output, null, 2)}
          </pre>
        </div>
      )}

      {/* ── Action bar ── */}
      <div className="flex gap-2">
        <button
          type="button"
          onClick={downloadTxt}
          className="flex-1 py-2.5 rounded-xl border border-border hover:border-primary/50 text-sm flex items-center justify-center gap-2 text-muted-foreground hover:text-foreground transition-colors"
        >
          <Download className="w-4 h-4" /> Download TXT
        </button>
        <button
          type="button"
          onClick={downloadJson}
          className="flex-1 py-2.5 rounded-xl border border-border hover:border-primary/50 text-sm flex items-center justify-center gap-2 text-muted-foreground hover:text-foreground transition-colors"
        >
          <Download className="w-4 h-4" /> Download JSON
        </button>
        <button
          type="button"
          onClick={onReset}
          className="py-2.5 px-4 rounded-xl border border-border hover:border-border/80 text-sm flex items-center justify-center gap-2 text-muted-foreground hover:text-foreground transition-colors"
          title="Buat storyboard baru"
        >
          <RotateCcw className="w-4 h-4" />
        </button>
      </div>
    </div>
  );
}
