"use client";

import { useState, useEffect } from "react";
import { toast } from "sonner";
import type {
  ExtractedProduct, UGCPackage,
  UGCPlatform, UGCLanguageStyle, UGCPresenter, UGCHookStyle,
} from "@/types/ugc-generator";
import { UGC_PLATFORMS } from "@/types/ugc-generator";

// ─── Default empty product ────────────────────────────────────────────────────
export const emptyProduct = (): ExtractedProduct => ({
  namaProduk: "", kategori: "", deskripsiProduk: "",
  masalahPainPoint: "", manfaatUtama: "", fiturKandungan: "",
  targetAudiens: "", harga: "", sourceUrl: "",
});

// ─── Hook ─────────────────────────────────────────────────────────────────────
export function useUGCGenerator() {
  // ── URL extract ──
  const [url, setUrl]               = useState("");
  const [extracting, setExtracting] = useState(false);
  const [extracted, setExtracted]   = useState(false);

  // ── Product ──
  const [product, setProduct] = useState<ExtractedProduct>(emptyProduct());
  const setField = (key: keyof ExtractedProduct, val: string) =>
    setProduct((p) => ({ ...p, [key]: val }));

  // ── Config ──
  const [platform, setPlatform]         = useState<UGCPlatform>("tiktok");
  const [durasi, setDurasi]             = useState("30s");
  const [gayaBahasa, setGayaBahasa]     = useState<UGCLanguageStyle>("santai_gaul");
  const [presenter, setPresenter]       = useState<UGCPresenter>("wanita");
  const [hookStyle, setHookStyle]       = useState<UGCHookStyle>("masalah_solusi");
  const [language, setLanguage]         = useState<"id" | "en">("id");
  const [showAdvanced, setShowAdvanced] = useState(false);
  const [brandVoice, setBrandVoice]     = useState("");
  const [customInstructions, setCustomInstructions] = useState("");

  // ── Output ──
  const [generating, setGenerating] = useState(false);
  const [output, setOutput]         = useState<UGCPackage | null>(null);

  // ── Derived ──
  const durasiOptions = UGC_PLATFORMS[platform]?.durations ?? ["30s", "60s"];

  // ── Session prefill (Templates page + Products Library) ──
  useEffect(() => {
    try {
      const rawConfig = sessionStorage.getItem("ugc_prefill");
      if (rawConfig) {
        const prefill = JSON.parse(rawConfig) as {
          platform?: UGCPlatform;
          gayaBahasa?: UGCLanguageStyle;
          hookStyle?: UGCHookStyle;
          durasi?: string;
        };
        if (prefill.platform)   setPlatform(prefill.platform);
        if (prefill.gayaBahasa) setGayaBahasa(prefill.gayaBahasa);
        if (prefill.hookStyle)  setHookStyle(prefill.hookStyle);
        if (prefill.durasi)     setDurasi(prefill.durasi);
        sessionStorage.removeItem("ugc_prefill");
        toast.success("Template UGC dimuat! Sesuaikan dan isi data produk.");
      }

      const rawProduct = sessionStorage.getItem("ugc_product_prefill");
      if (rawProduct) {
        const productData = JSON.parse(rawProduct) as ExtractedProduct;
        setProduct(productData);
        setExtracted(true);
        sessionStorage.removeItem("ugc_product_prefill");
        toast.success("Data produk dimuat dari library! Lengkapi dan generate UGC.");
      }
    } catch { /* ignore */ }
  }, []);

  // ── Extract dari URL ──────────────────────────────────────────────────────
  const handleExtract = async () => {
    if (!url.trim()) { toast.error("Masukkan URL produk terlebih dahulu"); return; }
    setExtracting(true);
    try {
      const res  = await fetch("/api/ugc-generator/extract", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ url: url.trim() }),
      });
      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 mengekstrak produk");
        return;
      }
      setProduct({ ...(data.data as ExtractedProduct) });
      setExtracted(true);
      toast.success("Data produk berhasil diekstrak! ✨ Periksa dan edit jika perlu.");
    } catch {
      toast.error("Gagal mengekstrak. Periksa koneksi internet.");
    } finally {
      setExtracting(false);
    }
  };

  // ── Generate UGC Package ─────────────────────────────────────────────────
  const handleGenerate = async () => {
    if (!product.namaProduk.trim())     { toast.error("Nama produk wajib diisi"); return; }
    if (!product.deskripsiProduk.trim()) { toast.error("Deskripsi produk wajib diisi"); return; }
    setGenerating(true);
    setOutput(null);
    try {
      const res  = await fetch("/api/ugc-generator", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          product, platform, durasi, gayaBahasa, presenter, hookStyle, language,
          brandVoice:         brandVoice         || undefined,
          customInstructions: customInstructions || undefined,
        }),
      });
      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 UGC Package");
        return;
      }
      setOutput(data.data as UGCPackage);
      toast.success("UGC Package berhasil dibuat! 🎉");
    } catch {
      toast.error("Terjadi kesalahan. Coba lagi.");
    } finally {
      setGenerating(false);
    }
  };

  const handleReset        = () => setOutput(null);
  const handleClearProduct = () => { setProduct(emptyProduct()); setExtracted(false); setUrl(""); };

  return {
    // URL extract
    url, setUrl, extracting, extracted, handleExtract,
    // Product
    product, setField, handleClearProduct,
    // Config
    platform, setPlatform,
    durasi, setDurasi, durasiOptions,
    gayaBahasa, setGayaBahasa,
    presenter, setPresenter,
    hookStyle, setHookStyle,
    language, setLanguage,
    showAdvanced, setShowAdvanced,
    brandVoice, setBrandVoice,
    customInstructions, setCustomInstructions,
    // Output
    generating, output, handleGenerate, handleReset,
  };
}
