"use client";

import { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import {
  Link2, Wand2, Loader2, Globe, Facebook, Instagram, Twitter,
  Clapperboard, Clock, Film, ChevronDown, Info,
} from "lucide-react";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import {
  STORYBOARD_STYLES,
  STORYBOARD_LENGTHS,
  SCENE_DURATION_PRESETS,
  TOTAL_DURATION_PRESETS,
  estimateSceneCount,
  type StoryboardStyle,
  type StoryboardLength,
  type SceneDurationPreset,
  type TotalDurationPreset,
  type StoryboardRequest,
  type StoryboardOutput,
} from "@/types/storyboard";

// ── Zod schema ─────────────────────────────────────────────────────────────────
const formSchema = z.object({
  url: z
    .string()
    .min(1, "URL tidak boleh kosong")
    .refine(
      (v) => { try { new URL(v.startsWith("http") ? v : `https://${v}`); return true; } catch { return false; } },
      { message: "Masukkan URL yang valid (contoh: https://example.com/artikel)" }
    ),
  tone: z.string().max(100).optional(),
  targetAudience: z.string().max(150).optional(),
  customInstructions: z.string().max(500).optional(),
  customSceneCount: z.coerce.number().int().min(1).max(30).optional(),
  customSceneDuration: z.string().max(30).optional(),
  customTotalDuration: z.string().max(30).optional(),
});
type FormValues = z.infer<typeof formSchema>;

// ── Platform detector ──────────────────────────────────────────────────────────
function detectPlatform(url: string): { icon: React.ReactNode; label: string; color: string } {
  const u = url.toLowerCase();
  if (u.includes("facebook.com") || u.includes("fb.com")) return { icon: <Facebook className="w-3.5 h-3.5" />, label: "Facebook", color: "text-blue-400" };
  if (u.includes("instagram.com")) return { icon: <Instagram className="w-3.5 h-3.5" />, label: "Instagram", color: "text-pink-400" };
  if (u.includes("twitter.com") || u.includes("x.com")) return { icon: <Twitter className="w-3.5 h-3.5" />, label: "Twitter / X", color: "text-sky-400" };
  if (url.length > 5) return { icon: <Globe className="w-3.5 h-3.5" />, label: "Website", color: "text-green-400" };
  return { icon: <Link2 className="w-3.5 h-3.5" />, label: "URL", color: "text-muted-foreground" };
}

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

// ── Component ──────────────────────────────────────────────────────────────────
export default function StoryboardForm({ onResult }: Props) {
  const [style, setStyle] = useState<StoryboardStyle>("cinematic");

  // Prefill from Templates page (sessionStorage)
  useEffect(() => {
    try {
      const raw = sessionStorage.getItem("storyboard_prefill");
      if (raw) {
        const prefill = JSON.parse(raw) as { style?: string };
        if (prefill.style && prefill.style in STORYBOARD_STYLES) {
          setStyle(prefill.style as StoryboardStyle);
        }
        sessionStorage.removeItem("storyboard_prefill");
      }
    } catch { /* ignore */ }
  }, []);
  const [length, setLength] = useState<StoryboardLength>("medium");
  const [language, setLanguage] = useState<"id" | "en">("id");
  const [sceneDurationPreset, setSceneDurationPreset] = useState<SceneDurationPreset>("3-5s");
  const [totalDurationPreset, setTotalDurationPreset] = useState<TotalDurationPreset>("30s");
  const [showAdvanced, setShowAdvanced] = useState(false);
  const [showDurationPanel, setShowDurationPanel] = useState(false);
  const [loading, setLoading] = useState(false);

  const {
    register,
    handleSubmit,
    watch,
    setValue,
    formState: { errors },
  } = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: { url: "", tone: "", targetAudience: "", customInstructions: "", customSceneCount: 6, customSceneDuration: "", customTotalDuration: "" },
  });

  const urlValue = watch("url");
  const customSceneCount = watch("customSceneCount");
  const customSceneDuration = watch("customSceneDuration");
  const customTotalDuration = watch("customTotalDuration");
  const platform = detectPlatform(urlValue || "");

  // Live estimate: scene count from total + scene duration
  const liveEstimate = (() => {
    if (length !== "custom") return null;
    if (totalDurationPreset === "custom" && customTotalDuration) {
      const sceneDurStr = sceneDurationPreset === "custom" ? customSceneDuration : SCENE_DURATION_PRESETS[sceneDurationPreset]?.value;
      if (sceneDurStr) {
        const n = estimateSceneCount(customTotalDuration, sceneDurStr);
        if (n) return `≈ ${n} scene`;
      }
    } else if (totalDurationPreset !== "custom") {
      const totalStr = TOTAL_DURATION_PRESETS[totalDurationPreset]?.value;
      const sceneDurStr = sceneDurationPreset === "custom" ? customSceneDuration : SCENE_DURATION_PRESETS[sceneDurationPreset]?.value;
      if (totalStr && sceneDurStr) {
        const n = estimateSceneCount(totalStr, sceneDurStr);
        if (n) return `≈ ${n} scene`;
      }
    }
    return null;
  })();

  const onSubmit = async (values: FormValues) => {
    setLoading(true);
    try {
      const payload: StoryboardRequest = {
        url: values.url,
        style,
        length,
        language,
        tone: values.tone || undefined,
        targetAudience: values.targetAudience || undefined,
        customInstructions: values.customInstructions || undefined,
        customSceneCount: length === "custom" ? values.customSceneCount : undefined,
        sceneDurationPreset,
        customSceneDuration: sceneDurationPreset === "custom" ? values.customSceneDuration || undefined : undefined,
        totalDurationPreset,
        customTotalDuration: totalDurationPreset === "custom" ? values.customTotalDuration || undefined : undefined,
      };

      const res = await fetch("/api/storyboard", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      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 storyboard");
        return;
      }

      toast.success("Storyboard berhasil dibuat! 🎬");
      onResult(data.data as StoryboardOutput);
    } catch {
      toast.error("Terjadi kesalahan. Periksa koneksi internet kamu.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">

      {/* ── URL Input ── */}
      <div className="glass-card rounded-xl p-4 space-y-3">
        <label className="text-sm font-medium flex items-center gap-2 mb-2">
          <Link2 className="w-4 h-4 text-primary" />
          Link Postingan / Artikel <span className="text-red-400">*</span>
        </label>
        <div className="relative">
          <input
            {...register("url")}
            placeholder="https://example.com/artikel atau link Facebook / Instagram / Twitter"
            className={cn(
              "w-full px-3 py-2.5 pr-28 rounded-lg bg-accent border focus:outline-none focus:ring-1 transition-colors text-sm",
              errors.url ? "border-red-400 focus:border-red-400 focus:ring-red-400" : "border-border focus:border-primary focus:ring-primary"
            )}
          />
          {urlValue && (
            <div className={cn("absolute right-3 top-1/2 -translate-y-1/2 flex items-center gap-1 text-xs font-medium", platform.color)}>
              {platform.icon}<span>{platform.label}</span>
            </div>
          )}
        </div>
        {errors.url && <p className="text-xs text-red-400 mt-1">{errors.url.message}</p>}
        <div className="flex items-center gap-3">
          <span className="text-xs text-muted-foreground">Didukung:</span>
          <div className="flex items-center gap-3">
            {[
              { icon: <Globe className="w-3 h-3" />, label: "Website", color: "text-green-400" },
              { icon: <Facebook className="w-3 h-3" />, label: "Facebook", color: "text-blue-400" },
              { icon: <Instagram className="w-3 h-3" />, label: "Instagram", color: "text-pink-400" },
              { icon: <Twitter className="w-3 h-3" />, label: "X/Twitter", color: "text-sky-400" },
            ].map((p) => (
              <span key={p.label} className={cn("flex items-center gap-1 text-xs", p.color)}>{p.icon}{p.label}</span>
            ))}
          </div>
        </div>
      </div>

      {/* ── Style selector ── */}
      <div className="glass-card rounded-xl p-4 space-y-3">
        <h3 className="text-sm font-medium text-muted-foreground flex items-center gap-2">
          <Clapperboard className="w-4 h-4" /> Style Storyboard
        </h3>
        <div className="grid grid-cols-2 gap-2">
          {(Object.entries(STORYBOARD_STYLES) as [StoryboardStyle, typeof STORYBOARD_STYLES[StoryboardStyle]][]).map(([key, info]) => (
            <button
              key={key}
              type="button"
              onClick={() => setStyle(key)}
              className={cn(
                "flex items-start gap-2.5 p-3 rounded-lg border text-left transition-all",
                style === key
                  ? "border-primary bg-primary/10 text-foreground"
                  : "border-border bg-accent/50 text-muted-foreground hover:border-primary/40 hover:text-foreground"
              )}
            >
              <span className="text-xl leading-none mt-0.5">{info.icon}</span>
              <div>
                <div className="text-xs font-medium leading-tight">{info.label}</div>
                <div className="text-[10px] text-muted-foreground mt-0.5 leading-tight">{info.description}</div>
              </div>
            </button>
          ))}
        </div>
      </div>

      {/* ── Scene count (length preset) ── */}
      <div className="glass-card rounded-xl p-4 space-y-3">
        <h3 className="text-sm font-medium text-muted-foreground flex items-center gap-2">
          <Film className="w-4 h-4" /> Jumlah Scene
        </h3>

        {/* Preset buttons */}
        <div className="grid grid-cols-4 gap-2">
          {(Object.entries(STORYBOARD_LENGTHS) as [StoryboardLength, typeof STORYBOARD_LENGTHS[StoryboardLength]][]).map(([key, info]) => (
            <button
              key={key}
              type="button"
              onClick={() => setLength(key)}
              className={cn(
                "flex flex-col items-center p-2.5 rounded-lg border text-center transition-all",
                length === key
                  ? "border-primary bg-primary/10 text-foreground"
                  : "border-border bg-accent/50 text-muted-foreground hover:border-primary/40 hover:text-foreground"
              )}
            >
              <span className={cn("text-sm font-semibold", key === "custom" && "text-violet-400")}>
                {key === "custom" ? "✏️" : info.scenes.split("–")[0]}
              </span>
              <span className="text-[10px] font-medium mt-0.5">{info.label}</span>
              {key !== "custom" && <span className="text-[9px] text-muted-foreground">{info.scenes}</span>}
              {key === "custom" && <span className="text-[9px] text-violet-400">Atur sendiri</span>}
            </button>
          ))}
        </div>

        {/* Custom scene count input */}
        {length === "custom" && (
          <div className="rounded-xl bg-violet-500/5 border border-violet-500/20 p-4 space-y-3">
            <div className="flex items-center gap-2 text-xs text-violet-300 font-medium">
              <Info className="w-3.5 h-3.5" /> Mode Custom — atur jumlah scene secara manual
            </div>
            <div className="flex items-center gap-3">
              <div className="flex-1">
                <label className="text-xs text-muted-foreground mb-1.5 block">Jumlah Scene (1–30)</label>
                <div className="flex items-center gap-2">
                  <button
                    type="button"
                    onClick={() => setValue("customSceneCount", Math.max(1, (customSceneCount ?? 6) - 1))}
                    className="w-8 h-8 rounded-lg bg-accent border border-border flex items-center justify-center text-sm hover:bg-accent/80 transition-colors"
                  >−</button>
                  <input
                    {...register("customSceneCount")}
                    type="number"
                    min={1}
                    max={30}
                    className="w-16 text-center px-2 py-1.5 rounded-lg bg-accent border border-border focus:border-primary focus:outline-none text-sm font-semibold"
                  />
                  <button
                    type="button"
                    onClick={() => setValue("customSceneCount", Math.min(30, (customSceneCount ?? 6) + 1))}
                    className="w-8 h-8 rounded-lg bg-accent border border-border flex items-center justify-center text-sm hover:bg-accent/80 transition-colors"
                  >+</button>
                  <span className="text-xs text-muted-foreground">scene</span>
                </div>
                {errors.customSceneCount && <p className="text-xs text-red-400 mt-1">{errors.customSceneCount.message}</p>}
              </div>
              {liveEstimate && (
                <div className="text-xs text-violet-300 bg-violet-500/10 rounded-lg px-3 py-2 text-center">
                  Estimasi<br /><span className="font-bold text-sm">{liveEstimate}</span>
                </div>
              )}
            </div>
            {/* Quick preset shortcuts */}
            <div className="flex gap-1.5 flex-wrap">
              <span className="text-xs text-muted-foreground self-center">Cepat:</span>
              {[3, 5, 7, 10, 12, 15, 20].map((n) => (
                <button
                  key={n}
                  type="button"
                  onClick={() => setValue("customSceneCount", n)}
                  className={cn(
                    "px-2.5 py-1 rounded-lg text-xs border transition-colors",
                    customSceneCount === n
                      ? "bg-violet-600 border-violet-500 text-white"
                      : "bg-accent border-border text-muted-foreground hover:text-foreground"
                  )}
                >
                  {n}
                </button>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* ── Duration customization ── */}
      <div className="glass-card rounded-xl overflow-hidden">
        <button
          type="button"
          onClick={() => setShowDurationPanel(!showDurationPanel)}
          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">
            <Clock className="w-4 h-4 text-cyan-400" />
            Kustomisasi Durasi
            {/* Summary badge */}
            <span className="text-xs text-muted-foreground font-normal ml-1">
              {(() => {
                const scene = sceneDurationPreset === "custom" ? (customSceneDuration || "–") : SCENE_DURATION_PRESETS[sceneDurationPreset]?.label;
                const total = totalDurationPreset === "custom" ? (customTotalDuration || "–") : TOTAL_DURATION_PRESETS[totalDurationPreset]?.label;
                return `${scene} / scene · total ${total}`;
              })()}
            </span>
          </div>
          <ChevronDown className={cn("w-4 h-4 text-muted-foreground transition-transform", showDurationPanel && "rotate-180")} />
        </button>

        {showDurationPanel && (
          <div className="px-4 pb-4 space-y-5 border-t border-border/40">
            {/* Scene duration */}
            <div className="pt-4 space-y-2.5">
              <div className="flex items-center justify-between">
                <label className="text-sm font-medium flex items-center gap-1.5">
                  ⏱ Durasi Per Scene
                </label>
                <span className="text-xs text-muted-foreground">Berapa lama setiap scene berlangsung?</span>
              </div>
              <div className="grid grid-cols-3 gap-2">
                {(Object.entries(SCENE_DURATION_PRESETS) as [SceneDurationPreset, typeof SCENE_DURATION_PRESETS[SceneDurationPreset]][]).map(([key, info]) => (
                  <button
                    key={key}
                    type="button"
                    onClick={() => setSceneDurationPreset(key)}
                    className={cn(
                      "py-2 px-3 rounded-lg border text-xs font-medium text-center transition-all",
                      sceneDurationPreset === key
                        ? "border-cyan-500 bg-cyan-500/10 text-cyan-300"
                        : "border-border bg-accent/50 text-muted-foreground hover:border-cyan-500/40 hover:text-foreground"
                    )}
                  >
                    {key === "custom" ? "✏️ Custom" : info.label}
                  </button>
                ))}
              </div>
              {sceneDurationPreset === "custom" && (
                <div>
                  <input
                    {...register("customSceneDuration")}
                    placeholder="misal: 4 detik, 6-8 detik, 10s..."
                    className="w-full px-3 py-2 rounded-lg bg-accent border border-cyan-500/30 focus:border-cyan-500 focus:outline-none text-sm"
                  />
                  <p className="text-xs text-muted-foreground mt-1">Format bebas: "4 detik", "5-7s", "10 sec", dll.</p>
                </div>
              )}
            </div>

            {/* Divider */}
            <div className="h-px bg-border/40" />

            {/* Total duration */}
            <div className="space-y-2.5">
              <div className="flex items-center justify-between">
                <label className="text-sm font-medium flex items-center gap-1.5">
                  🎬 Total Durasi Video
                </label>
                <span className="text-xs text-muted-foreground">Target panjang video akhir</span>
              </div>
              <div className="grid grid-cols-3 gap-2">
                {(Object.entries(TOTAL_DURATION_PRESETS) as [TotalDurationPreset, typeof TOTAL_DURATION_PRESETS[TotalDurationPreset]][]).map(([key, info]) => (
                  <button
                    key={key}
                    type="button"
                    onClick={() => setTotalDurationPreset(key)}
                    className={cn(
                      "py-2 px-3 rounded-lg border text-xs font-medium text-center transition-all",
                      totalDurationPreset === key
                        ? "border-emerald-500 bg-emerald-500/10 text-emerald-300"
                        : "border-border bg-accent/50 text-muted-foreground hover:border-emerald-500/40 hover:text-foreground"
                    )}
                  >
                    {key === "custom" ? "✏️ Custom" : info.label}
                  </button>
                ))}
              </div>
              {totalDurationPreset === "custom" && (
                <div>
                  <input
                    {...register("customTotalDuration")}
                    placeholder="misal: 45 detik, 2 menit, 90s..."
                    className="w-full px-3 py-2 rounded-lg bg-accent border border-emerald-500/30 focus:border-emerald-500 focus:outline-none text-sm"
                  />
                  <p className="text-xs text-muted-foreground mt-1">Format bebas: "45 detik", "2 menit", "90s", dll.</p>
                </div>
              )}
            </div>

            {/* Live summary */}
            <div className="rounded-xl bg-accent/60 border border-border/60 p-3 grid grid-cols-3 gap-3 text-center">
              <div>
                <p className="text-[10px] text-muted-foreground mb-1">Scene</p>
                <p className="text-sm font-semibold text-foreground">
                  {length === "custom"
                    ? (customSceneCount ? `${customSceneCount}` : "–")
                    : STORYBOARD_LENGTHS[length]?.scenes ?? "–"}
                </p>
              </div>
              <div className="border-x border-border/40">
                <p className="text-[10px] text-muted-foreground mb-1">Durasi/Scene</p>
                <p className="text-sm font-semibold text-cyan-300">
                  {sceneDurationPreset === "custom"
                    ? (customSceneDuration || "–")
                    : SCENE_DURATION_PRESETS[sceneDurationPreset]?.label ?? "–"}
                </p>
              </div>
              <div>
                <p className="text-[10px] text-muted-foreground mb-1">Total</p>
                <p className="text-sm font-semibold text-emerald-300">
                  {totalDurationPreset === "custom"
                    ? (customTotalDuration || "–")
                    : TOTAL_DURATION_PRESETS[totalDurationPreset]?.label ?? "–"}
                </p>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* ── Language ── */}
      <div className="glass-card rounded-xl p-3 flex items-center gap-4">
        <span className="text-xs text-muted-foreground">Bahasa Output:</span>
        <div className="flex rounded-lg bg-accent overflow-hidden">
          {(["id", "en"] as const).map((lang) => (
            <button
              key={lang}
              type="button"
              onClick={() => setLanguage(lang)}
              className={cn(
                "px-3 py-1.5 text-xs font-medium transition-colors",
                language === lang ? "bg-primary text-primary-foreground" : "text-muted-foreground hover:text-foreground"
              )}
            >
              {lang === "id" ? "🇮🇩 Bahasa Indonesia" : "🇬🇧 English"}
            </button>
          ))}
        </div>
      </div>

      {/* ── Advanced Options ── */}
      <div className="glass-card rounded-xl overflow-hidden">
        <button
          type="button"
          onClick={() => setShowAdvanced(!showAdvanced)}
          className="w-full flex items-center justify-between px-4 py-3 text-sm text-muted-foreground hover:text-foreground transition-colors"
        >
          <span className="font-medium">Opsi Lanjutan</span>
          <ChevronDown className={cn("w-4 h-4 transition-transform", showAdvanced && "rotate-180")} />
        </button>
        {showAdvanced && (
          <div className="px-4 pb-4 space-y-3 border-t border-border/40">
            <div className="pt-3">
              <label className="text-xs text-muted-foreground mb-1.5 block">Tone Tambahan</label>
              <input {...register("tone")} placeholder="misal: inspiratif, serius, santai, profesional..."
                className="w-full px-3 py-2 rounded-lg bg-accent border border-border focus:border-primary focus:outline-none text-sm" />
            </div>
            <div>
              <label className="text-xs text-muted-foreground mb-1.5 block">Target Audience</label>
              <input {...register("targetAudience")} placeholder="misal: pengusaha muda 25-35 tahun, ibu rumah tangga..."
                className="w-full px-3 py-2 rounded-lg bg-accent border border-border focus:border-primary focus:outline-none text-sm" />
            </div>
            <div>
              <label className="text-xs text-muted-foreground mb-1.5 block">Instruksi Khusus</label>
              <textarea {...register("customInstructions")} placeholder="Arahan tambahan untuk AI, misal: fokus pada kisah transformasi, tambahkan statistik, dll."
                rows={3} className="w-full px-3 py-2 rounded-lg bg-accent border border-border focus:border-primary focus:outline-none text-sm resize-none" />
            </div>
          </div>
        )}
      </div>

      {/* ── Submit ── */}
      <div className="sticky bottom-0 bg-background/80 backdrop-blur-sm pb-2 -mx-1 px-1">
        <button
          type="submit"
          disabled={loading}
          className="w-full py-3.5 rounded-xl bg-gradient-to-r from-violet-600 via-purple-600 to-blue-600 text-white font-semibold hover:opacity-90 transition-all disabled:opacity-50 flex items-center justify-center gap-2 shadow-lg shadow-violet-500/25"
        >
          {loading
            ? <><Loader2 className="w-4 h-4 animate-spin" />Mengambil konten & membuat storyboard...</>
            : <><Wand2 className="w-4 h-4" />Buat Storyboard</>}
        </button>
        {loading && <p className="text-center text-xs text-muted-foreground mt-2">Mengambil konten dari URL lalu memproses dengan AI... (~15-30 detik)</p>}
      </div>
    </form>
  );
}
