"use client";

import { useState, useEffect } from "react";
import { Plus, Package, Trash2, Edit2, Search, Film, ArrowRight } from "lucide-react";
import { toast } from "sonner";
import { useRouter } from "next/navigation";
import { createClient } from "@/lib/supabase/client";
import type { Product } from "@/types";

export default function ProductsPage() {
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [editProduct, setEditProduct] = useState<Product | null>(null);
  const [search, setSearch] = useState("");
  const supabase = createClient();
  const router = useRouter();

  useEffect(() => { fetchProducts(); }, []);

  async function fetchProducts() {
    const { data: { user } } = await supabase.auth.getUser();
    if (!user) return;

    const { data } = await supabase
      .from("products")
      .select("*")
      .eq("user_id", user.id)
      .order("created_at", { ascending: false });

    setProducts(data ?? []);
    setLoading(false);
  }

  async function deleteProduct(id: string) {
    if (!confirm("Hapus produk ini?")) return;
    await supabase.from("products").delete().eq("id", id);
    setProducts((prev) => prev.filter((p) => p.id !== id));
    toast.success("Produk dihapus");
  }

  function useForUGC(product: Product) {
    // Pre-fill UGC generator dengan data produk dari library
    sessionStorage.setItem("ugc_product_prefill", JSON.stringify({
      namaProduk:      product.name,
      kategori:        product.category ?? "",
      deskripsiProduk: product.description ?? "",
      masalahPainPoint: "",
      manfaatUtama:    "",
      fiturKandungan:  "",
      targetAudiens:   "",
      harga:           "",
      imageUrl:        product.image_url ?? undefined,
      sourceUrl:       "",
    }));
    router.push("/ugc-generator");
    toast.success(`${product.name} dimuat ke UGC Generator!`);
  }

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

  return (
    <div className="max-w-4xl mx-auto space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Product Library</h1>
          <p className="text-muted-foreground text-sm mt-1">
            Simpan informasi produk untuk digunakan saat generate prompt
          </p>
        </div>
        <button
          onClick={() => { setEditProduct(null); setShowModal(true); }}
          className="flex items-center gap-2 px-4 py-2 rounded-xl bg-primary text-primary-foreground text-sm font-medium hover:opacity-90 transition-opacity"
        >
          <Plus className="w-4 h-4" /> Tambah Produk
        </button>
      </div>

      {/* Search */}
      <div className="relative">
        <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 produk..."
          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>

      {loading ? (
        <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-4">
          {[1, 2, 3].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-16 text-muted-foreground">
          <Package className="w-12 h-12 mx-auto mb-3 opacity-30" />
          <p className="font-medium">Belum ada produk</p>
          <p className="text-sm mt-1">Tambahkan produk untuk mempercepat pembuatan prompt.</p>
        </div>
      ) : (
        <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-4">
          {filtered.map((product) => (
            <div key={product.id} className="glass-card rounded-xl overflow-hidden group">
              {product.image_url ? (
                <img src={product.image_url} alt={product.name} className="w-full h-32 object-cover" />
              ) : (
                <div className="w-full h-32 bg-accent flex items-center justify-center">
                  <Package className="w-8 h-8 text-muted-foreground" />
                </div>
              )}
              <div className="p-3">
                <div className="flex items-start justify-between gap-2">
                  <div className="flex-1 min-w-0">
                    <p className="font-medium text-sm">{product.name}</p>
                    {product.category && (
                      <span className="text-xs text-muted-foreground">{product.category}</span>
                    )}
                    {product.description && (
                      <p className="text-xs text-muted-foreground mt-1 line-clamp-2">{product.description}</p>
                    )}
                  </div>
                  <div className="flex gap-1 flex-shrink-0 opacity-0 group-hover:opacity-100 transition-opacity">
                    <button
                      onClick={() => { setEditProduct(product); setShowModal(true); }}
                      className="w-7 h-7 rounded flex items-center justify-center hover:bg-accent text-muted-foreground hover:text-foreground"
                      title="Edit produk"
                    >
                      <Edit2 className="w-3.5 h-3.5" />
                    </button>
                    <button
                      onClick={() => deleteProduct(product.id)}
                      className="w-7 h-7 rounded flex items-center justify-center hover:bg-red-500/10 text-muted-foreground hover:text-red-400"
                      title="Hapus produk"
                    >
                      <Trash2 className="w-3.5 h-3.5" />
                    </button>
                  </div>
                </div>
                {/* UGC shortcut */}
                <button
                  onClick={() => useForUGC(product)}
                  className="mt-3 w-full flex items-center justify-center gap-1.5 py-2 rounded-lg text-xs font-medium border border-pink-500/30 text-pink-300 hover:bg-pink-500/10 transition-all opacity-0 group-hover:opacity-100"
                >
                  <Film className="w-3.5 h-3.5" />
                  Buat UGC
                  <ArrowRight className="w-3 h-3" />
                </button>
              </div>
            </div>
          ))}
        </div>
      )}

      {showModal && (
        <ProductModal
          product={editProduct}
          onClose={() => setShowModal(false)}
          onSave={() => { fetchProducts(); setShowModal(false); }}
        />
      )}
    </div>
  );
}

function ProductModal({ product, onClose, onSave }: {
  product: Product | null;
  onClose: () => void;
  onSave: () => void;
}) {
  const [name, setName] = useState(product?.name ?? "");
  const [description, setDescription] = useState(product?.description ?? "");
  const [category, setCategory] = useState(product?.category ?? "");
  const [saving, setSaving] = useState(false);
  const supabase = createClient();

  async function handleSave() {
    if (!name.trim()) { toast.error("Nama produk wajib diisi"); return; }
    setSaving(true);
    try {
      const { data: { user } } = await supabase.auth.getUser();
      if (!user) return;

      if (product) {
        await supabase.from("products").update({ name, description, category }).eq("id", product.id);
        toast.success("Produk diupdate");
      } else {
        await supabase.from("products").insert({ name, description, category, user_id: user.id });
        toast.success("Produk ditambahkan");
      }
      onSave();
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="fixed inset-0 bg-background/80 backdrop-blur-sm z-50 flex items-center justify-center p-4">
      <div className="bg-card border border-border rounded-2xl p-6 w-full max-w-md">
        <h2 className="font-bold text-lg mb-4">{product ? "Edit Produk" : "Tambah Produk"}</h2>
        <div className="space-y-4">
          <div>
            <label className="text-sm font-medium mb-1.5 block">Nama Produk *</label>
            <input value={name} onChange={(e) => setName(e.target.value)}
              className="w-full px-3 py-2.5 rounded-lg bg-accent border border-border focus:border-primary focus:outline-none text-sm" />
          </div>
          <div>
            <label className="text-sm font-medium mb-1.5 block">Kategori</label>
            <input value={category} onChange={(e) => setCategory(e.target.value)}
              placeholder="misal: skincare, fashion, food..."
              className="w-full px-3 py-2.5 rounded-lg bg-accent border border-border focus:border-primary focus:outline-none text-sm" />
          </div>
          <div>
            <label className="text-sm font-medium mb-1.5 block">Deskripsi</label>
            <textarea value={description} onChange={(e) => setDescription(e.target.value)}
              rows={3} className="w-full px-3 py-2.5 rounded-lg bg-accent border border-border focus:border-primary focus:outline-none text-sm resize-none" />
          </div>
        </div>
        <div className="flex gap-3 mt-6">
          <button onClick={onClose} className="flex-1 py-2.5 rounded-xl border border-border text-sm hover:bg-accent transition-colors">Batal</button>
          <button onClick={handleSave} disabled={saving}
            className="flex-1 py-2.5 rounded-xl bg-primary text-primary-foreground text-sm font-medium hover:opacity-90 transition-opacity disabled:opacity-60">
            {saving ? "Menyimpan..." : "Simpan"}
          </button>
        </div>
      </div>
    </div>
  );
}
