"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { BookTemplate, ArrowRight, Star, Search, Clapperboard, Film } from "lucide-react";
import { toast } from "sonner";
import { PLATFORM_CONFIGS } from "@/types";
import type { PromptTemplate } from "@/types";
import { STORYBOARD_STYLES } from "@/types/storyboard";
import { cn } from "@/lib/utils";

// ── UGC starter templates ──────────────────────────────────────────────────────
const UGC_STARTERS = [
  {
    id: "ugc-tiktok-santai",
    icon: "📱",
    platform: "tiktok",
    gayaBahasa: "santai_gaul",
    hookStyle: "masalah_solusi",
    durasi: "30s",
    label: "TikTok · Santai/Gaul",
    desc: "Script kasual anak muda, cocok untuk skincare, fashion, F&B. Hook masalah → solusi.",
  },
  {
    id: "ugc-shopee-testimoni",
    icon: "🛍️",
    platform: "shopee_video",
    gayaBahasa: "emosional_cerita",
    hookStyle: "testimoni",
    durasi: "30s",
    label: "Shopee Video · Testimoni",
    desc: "Review autentik gaya testimoni untuk boost konversi di Shopee Live.",
  },
  {
    id: "ugc-ig-energik",
    icon: "📸",
    platform: "instagram_reels",
    gayaBahasa: "energik_hype",
    hookStyle: "shocking_fact",
    durasi: "15s",
    label: "IG Reels · Energik/Hype",
    desc: "Konten cepat & high energy dengan fakta mengejutkan di 3 detik pertama.",
  },
  {
    id: "ugc-yt-edukatif",
    icon: "▶️",
    platform: "youtube_shorts",
    gayaBahasa: "informatif_edukatif",
    hookStyle: "pertanyaan",
    durasi: "60s",
    label: "YouTube Shorts · Edukatif",
    desc: "Review detail dan informatif untuk produk yang butuh penjelasan lebih panjang.",
  },
  {
    id: "ugc-tiktok-before-after",
    icon: "✨",
    platform: "tiktok",
    gayaBahasa: "emosional_cerita",
    hookStyle: "before_after",
    durasi: "60s",
    label: "TikTok · Before & After",
    desc: "Transformasi visual dramatis. Sangat efektif untuk beauty, wellness, produk perawatan.",
  },
  {
    id: "ugc-fb-formal",
    icon: "👥",
    platform: "facebook_reels",
    gayaBahasa: "formal_profesional",
    hookStyle: "challenge",
    durasi: "30s",
    label: "FB Reels · Profesional",
    desc: "Gaya formal dengan garansi/challenge, cocok untuk produk kesehatan atau B2B.",
  },
];

// ── Storyboard starter templates (pre-filled suggestions, client-only) ─────────
const STORYBOARD_STARTERS = [
  {
    id: "sb-cinematic",
    icon: "🎬",
    style: "cinematic",
    label: "Cinematic — Kisah Inspiratif",
    description: "Cocok untuk artikel motivasi, kisah sukses, atau transformasi personal.",
    url: "",
  },
  {
    id: "sb-social",
    icon: "📱",
    style: "social",
    label: "Social Media — Viral Content",
    description: "Storyboard pendek & catchy untuk TikTok / Instagram Reels. 5–7 scene.",
    url: "",
  },
  {
    id: "sb-explainer",
    icon: "💡",
    style: "explainer",
    label: "Explainer — Edukasi & Tutorial",
    description: "Ubah artikel how-to atau tips menjadi video explainer step-by-step.",
    url: "",
  },
  {
    id: "sb-documentary",
    icon: "📹",
    style: "documentary",
    label: "Dokumenter — Berita & Fakta",
    description: "Untuk artikel berita, investigasi, atau konten berbasis data.",
    url: "",
  },
  {
    id: "sb-emotional",
    icon: "💖",
    style: "emotional",
    label: "Emotional — Cerita Menyentuh",
    description: "Cocok untuk kisah personal, charity, atau konten human-interest.",
    url: "",
  },
  {
    id: "sb-humor",
    icon: "😄",
    style: "humor",
    label: "Humoris — Konten Ringan",
    description: "Storyboard santai dan menghibur untuk konten entertaining.",
    url: "",
  },
];

export default function TemplatesPage() {
  const [templates, setTemplates] = useState<PromptTemplate[]>([]);
  const [loading, setLoading]     = useState(true);
  const [filter, setFilter]       = useState("all");
  const [search, setSearch]       = useState("");
  const router = useRouter();

  useEffect(() => {
    fetchTemplates();
  }, [filter]);

  async function fetchTemplates() {
    setLoading(true);
    try {
      const params = new URLSearchParams();
      if (filter !== "all") params.set("platform", filter);
      const res  = await fetch(`/api/templates?${params}`);
      const data = await res.json();
      setTemplates(data.data ?? []);
    } catch {
      toast.error("Gagal memuat templates");
    } finally {
      setLoading(false);
    }
  }

  async function useTemplate(template: PromptTemplate) {
    const platform = template.platform === "all" ? "seedance" : template.platform;
    sessionStorage.setItem("template_input", JSON.stringify(template.input_data));
    router.push(`/generator/${platform}`);
    toast.success("Template dimuat!");

    // Increment use_count di background — fire-and-forget, tidak block navigasi
    fetch("/api/templates", {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ id: template.id, use_count_increment: true }),
    }).catch(() => {/* silent — non-critical */});
  }

  function useStoryboardStarter(style: string) {
    // Pre-fill style in sessionStorage, then go to storyboard page
    sessionStorage.setItem("storyboard_prefill", JSON.stringify({ style }));
    router.push("/storyboard");
    toast.success("Template storyboard dimuat! Tinggal masukkan URL.");
  }

  function useUGCStarter(starter: typeof UGC_STARTERS[0]) {
    sessionStorage.setItem("ugc_prefill", JSON.stringify({
      platform:   starter.platform,
      gayaBahasa: starter.gayaBahasa,
      hookStyle:  starter.hookStyle,
      durasi:     starter.durasi,
    }));
    router.push("/ugc-generator");
    toast.success("Template UGC dimuat! Tinggal isi data produk.");
  }

  const filtered = templates.filter((t) => {
    if (!search) return true;
    const q = search.toLowerCase();
    return t.name.toLowerCase().includes(q) || t.description?.toLowerCase().includes(q);
  });

  const grouped = filtered.reduce((acc, t) => {
    const key = t.is_official ? "official" : "community";
    if (!acc[key]) acc[key] = [];
    acc[key].push(t);
    return acc;
  }, {} as Record<string, PromptTemplate[]>);

  return (
    <div className="max-w-5xl mx-auto space-y-8">
      <div>
        <h1 className="text-2xl font-bold">Templates</h1>
        <p className="text-muted-foreground text-sm mt-1">
          Mulai lebih cepat dengan template siap pakai
        </p>
      </div>

      {/* ── UGC Generator Starters ── */}
      <div>
        <div className="flex items-center gap-3 mb-4">
          <Film className="w-4 h-4 text-pink-400" />
          <h2 className="font-bold text-lg">UGC Generator Starter</h2>
          <span className="text-xs font-bold px-2 py-0.5 rounded-full bg-gradient-to-r from-pink-600 to-violet-600 text-white">NEW</span>
          <div className="flex-1 h-px" style={{ background: "rgba(236,72,153,0.2)" }} />
        </div>
        <p className="text-xs text-muted-foreground mb-4">
          Pilih template sesuai platform &amp; gaya konten, lalu isi atau paste link produk di halaman Generator UGC.
        </p>
        <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-3">
          {UGC_STARTERS.map((starter) => (
            <button
              key={starter.id}
              onClick={() => useUGCStarter(starter)}
              className="group rounded-xl p-4 text-left transition-all hover:-translate-y-0.5"
              style={{
                background: "linear-gradient(135deg, rgba(236,72,153,0.08), rgba(124,58,237,0.04))",
                border: "1px solid rgba(236,72,153,0.2)",
              }}
              onMouseEnter={(e) => {
                (e.currentTarget as HTMLButtonElement).style.border = "1px solid rgba(236,72,153,0.4)";
                (e.currentTarget as HTMLButtonElement).style.boxShadow = "0 4px 20px rgba(236,72,153,0.15)";
              }}
              onMouseLeave={(e) => {
                (e.currentTarget as HTMLButtonElement).style.border = "1px solid rgba(236,72,153,0.2)";
                (e.currentTarget as HTMLButtonElement).style.boxShadow = "";
              }}
            >
              <div className="flex items-start gap-3 mb-2">
                <span className="text-2xl flex-shrink-0">{starter.icon}</span>
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-semibold text-pink-200 truncate">{starter.label}</p>
                  <p className="text-xs text-muted-foreground mt-1 line-clamp-2">{starter.desc}</p>
                </div>
              </div>
              <div className="flex items-center gap-1 text-xs text-pink-400 opacity-0 group-hover:opacity-100 transition-opacity mt-1">
                Gunakan template ini <ArrowRight className="w-3 h-3" />
              </div>
            </button>
          ))}
        </div>
      </div>

      {/* ── Storyboard Starters ── */}
      <div>
        <div className="flex items-center gap-3 mb-4">
          <Clapperboard className="w-4 h-4 text-violet-400" />
          <h2 className="font-bold text-lg">Storyboard Starter</h2>
          <span className="text-xs font-bold px-2 py-0.5 rounded-full bg-gradient-to-r from-violet-600 to-blue-600 text-white">NEW</span>
          <div className="flex-1 h-px" style={{ background: "rgba(124,58,237,0.2)" }} />
        </div>
        <p className="text-xs text-muted-foreground mb-4">
          Pilih style yang sesuai konten kamu, lalu paste link artikel / postingan di halaman Storyboard.
        </p>
        <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-3">
          {STORYBOARD_STARTERS.map((starter) => {
            const styleInfo = STORYBOARD_STYLES[starter.style as keyof typeof STORYBOARD_STYLES];
            return (
              <button
                key={starter.id}
                onClick={() => useStoryboardStarter(starter.style)}
                className="group rounded-xl p-4 text-left transition-all hover:-translate-y-0.5 hover:shadow-lg"
                style={{
                  background: "linear-gradient(135deg, rgba(124,58,237,0.08), rgba(37,99,235,0.04))",
                  border: "1px solid rgba(124,58,237,0.2)",
                }}
                onMouseEnter={(e) => {
                  (e.currentTarget as HTMLButtonElement).style.border = "1px solid rgba(124,58,237,0.4)";
                  (e.currentTarget as HTMLButtonElement).style.boxShadow = "0 4px 20px rgba(124,58,237,0.15)";
                }}
                onMouseLeave={(e) => {
                  (e.currentTarget as HTMLButtonElement).style.border = "1px solid rgba(124,58,237,0.2)";
                  (e.currentTarget as HTMLButtonElement).style.boxShadow = "";
                }}
              >
                <div className="flex items-start gap-3 mb-2">
                  <span className="text-2xl flex-shrink-0">{styleInfo?.icon ?? starter.icon}</span>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-semibold text-violet-200 truncate">{starter.label}</p>
                    <p className="text-xs text-muted-foreground mt-1 line-clamp-2">{starter.description}</p>
                  </div>
                </div>
                <div className="flex items-center gap-1 text-xs text-violet-400 opacity-0 group-hover:opacity-100 transition-opacity mt-1">
                  Gunakan template ini <ArrowRight className="w-3 h-3" />
                </div>
              </button>
            );
          })}
        </div>
      </div>

      {/* ── Prompt Generator Templates ── */}
      <div>
        <div className="flex items-center gap-3 mb-4">
          <h2 className="font-bold text-lg">Template Prompt Generator</h2>
          <div className="flex-1 gold-hr-soft" />
        </div>

        {/* Filters */}
        <div className="flex flex-wrap gap-3 mb-5">
          <div className="relative flex-1 min-w-[200px]">
            <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 template..."
              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>
          <div className="flex gap-1.5 flex-wrap">
            {[{ value: "all", label: "Semua" }, ...Object.values(PLATFORM_CONFIGS).map((p) => ({ value: p.id, label: p.name }))].map((p) => (
              <button
                key={p.value}
                onClick={() => setFilter(p.value)}
                className={cn(
                  "px-3 py-1.5 rounded-lg text-xs font-medium transition-colors",
                  filter === p.value
                    ? "bg-primary text-primary-foreground"
                    : "bg-card border border-border text-muted-foreground hover:text-foreground"
                )}
              >
                {p.label}
              </button>
            ))}
          </div>
        </div>

        {loading ? (
          <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-4">
            {[1, 2, 3, 4, 5, 6].map((i) => <div key={i} className="h-40 rounded-xl bg-card border border-border animate-pulse" />)}
          </div>
        ) : filtered.length === 0 ? (
          <div className="text-center py-12 text-muted-foreground">
            <BookTemplate className="w-12 h-12 mx-auto mb-3 opacity-30" />
            <p className="font-medium">Belum ada template prompt</p>
            <p className="text-sm mt-1">Template akan ditambahkan oleh tim kami.</p>
          </div>
        ) : (
          <div className="space-y-8">
            {grouped.official && grouped.official.length > 0 && (
              <div>
                <div className="flex items-center gap-2 mb-4">
                  <Star className="w-4 h-4 text-yellow-400" />
                  <h3 className="font-bold">Template Resmi</h3>
                </div>
                <TemplateGrid templates={grouped.official} onUse={useTemplate} />
              </div>
            )}
            {grouped.community && grouped.community.length > 0 && (
              <div>
                <h3 className="font-bold mb-4">Template Komunitas</h3>
                <TemplateGrid templates={grouped.community} onUse={useTemplate} />
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

function TemplateGrid({ templates, onUse }: { templates: PromptTemplate[]; onUse: (t: PromptTemplate) => void }) {
  return (
    <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-4">
      {templates.map((template) => {
        const platform = template.platform !== "all"
          ? PLATFORM_CONFIGS[template.platform as keyof typeof PLATFORM_CONFIGS]
          : null;
        return (
          <div key={template.id} className="glass-card rounded-xl p-4 hover:border-primary/50 transition-all group">
            <div className="flex items-start gap-3 mb-3">
              <span className="text-2xl">{platform?.icon ?? "🎯"}</span>
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-1.5 mb-1">
                  {template.is_official && <Star className="w-3 h-3 text-yellow-400 fill-current flex-shrink-0" />}
                  <p className="font-medium text-sm truncate">{template.name}</p>
                </div>
                <p className="text-xs text-muted-foreground line-clamp-2">
                  {template.description ?? "Template siap pakai"}
                </p>
              </div>
            </div>
            {template.tags && template.tags.length > 0 && (
              <div className="flex flex-wrap gap-1 mb-3">
                {template.tags.slice(0, 3).map((tag) => (
                  <span key={tag} className="text-xs px-2 py-0.5 rounded-full bg-accent text-muted-foreground">{tag}</span>
                ))}
              </div>
            )}
            <div className="flex items-center justify-between">
              <span className="text-xs text-muted-foreground">{template.use_count} digunakan</span>
              <button onClick={() => onUse(template)}
                className="flex items-center gap-1.5 text-xs text-primary hover:underline opacity-0 group-hover:opacity-100 transition-opacity">
                Gunakan <ArrowRight className="w-3 h-3" />
              </button>
            </div>
          </div>
        );
      })}
    </div>
  );
}
