"use client";

import { useState, useEffect, useRef, use } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { ArrowLeft, Plus, Trash2, Loader2, Save, Upload, X } from "lucide-react";
import toast from "react-hot-toast";

interface Category { id: string; name: string }
interface Brand { id: string; name: string }

export default function EditProductPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params);
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [fetching, setFetching] = useState(true);
  const [categories, setCategories] = useState<Category[]>([]);
  const [brands, setBrands] = useState<Brand[]>([]);
  const [specs, setSpecs] = useState([{ label: "", value: "" }]);
  const [tags, setTags] = useState("");
  const [images, setImages] = useState([""]);
  const [uploadingIdx, setUploadingIdx] = useState<number | null>(null);
  const fileInputRefs = useRef<(HTMLInputElement | null)[]>([]);
  const [form, setForm] = useState({
    name: "", slug: "", description: "", shortDesc: "", price: "", comparePrice: "",
    costPrice: "", sku: "", stock: "0", categoryId: "", brandId: "",
    condition: "Brand New", featured: false, isNew: false, isHot: false, status: "ACTIVE",
  });

  useEffect(() => {
    Promise.all([
      fetch(`/api/admin/products/${id}`).then((r) => r.json()),
      fetch("/api/admin/categories").then((r) => r.json()),
      fetch("/api/admin/brands").then((r) => r.json()),
    ]).then(([product, cats, brds]) => {
      setCategories(cats);
      setBrands(brds);
      if (product && !product.error) {
        setForm({
          name: product.name || "", slug: product.slug || "",
          description: product.description || "", shortDesc: product.shortDesc || "",
          price: String(product.price || ""), comparePrice: product.comparePrice ? String(product.comparePrice) : "",
          costPrice: product.costPrice ? String(product.costPrice) : "",
          sku: product.sku || "", stock: String(product.stock || 0),
          categoryId: product.categoryId || "", brandId: product.brandId || "",
          condition: product.condition || "Brand New", featured: product.featured || false,
          isNew: product.isNew || false, isHot: product.isHot || false, status: product.status || "ACTIVE",
        });
        setImages(product.images?.length ? product.images : [""]);
        setSpecs(product.specs?.length ? product.specs.map((s: { label: string; value: string }) => ({ label: s.label, value: s.value })) : [{ label: "", value: "" }]);
        setTags(product.tags?.map((t: { tag: string }) => t.tag).join(", ") || "");
      }
      setFetching(false);
    });
  }, [id]);

  const update = (k: string, v: string | boolean) => setForm((f) => ({ ...f, [k]: v }));

  const handleFileUpload = async (file: File, idx: number) => {
    setUploadingIdx(idx);
    try {
      const fd = new FormData();
      fd.append("file", file);
      const res = await fetch("/api/admin/upload", { method: "POST", body: fd });
      const text = await res.text();
      const data = text ? JSON.parse(text) : {};
      if (!res.ok) throw new Error(data.error || `Upload failed (HTTP ${res.status})`);
      if (!data.url) throw new Error("No URL returned from server");
      const arr = [...images];
      arr[idx] = data.url;
      setImages(arr);
      toast.success("Image uploaded!");
    } catch (err) {
      toast.error((err as Error).message || "Upload failed");
    } finally {
      setUploadingIdx(null);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    try {
      const res = await fetch(`/api/admin/products/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          ...form,
          price: parseFloat(form.price),
          comparePrice: form.comparePrice ? parseFloat(form.comparePrice) : null,
          costPrice: form.costPrice ? parseFloat(form.costPrice) : null,
          stock: parseInt(form.stock),
          images: images.filter(Boolean),
          specs: specs.filter((s) => s.label && s.value),
          tags: tags.split(",").map((t) => t.trim()).filter(Boolean),
        }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error);
      toast.success("Product updated!");
      router.push("/admin/products");
    } catch (err) {
      toast.error((err as Error).message || "Failed to update");
    } finally {
      setLoading(false);
    }
  };

  const inputCls = "w-full px-4 py-2.5 rounded-xl border-2 border-slate-200 focus:border-sky-400 focus:outline-none text-sm transition-colors text-slate-900 bg-white placeholder:text-slate-400";
  const labelCls = "block text-sm font-bold text-slate-700 mb-1.5";

  if (fetching) return <div className="flex justify-center py-20"><Loader2 className="w-8 h-8 animate-spin text-sky-500" /></div>;

  return (
    <div className="max-w-4xl mx-auto">
      <div className="flex items-center gap-3 mb-6">
        <Link href="/admin/products" className="p-2 rounded-xl border border-slate-200 hover:bg-slate-50">
          <ArrowLeft className="w-4 h-4 text-slate-600" />
        </Link>
        <div>
          <h1 className="text-2xl font-black text-slate-900">Edit Product</h1>
          <p className="text-slate-500 text-sm line-clamp-1">{form.name}</p>
        </div>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        <div className="bg-white rounded-2xl border border-slate-100 p-6">
          <h2 className="font-black text-slate-800 mb-4">Basic Information</h2>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div className="sm:col-span-2">
              <label className={labelCls}>Product Name *</label>
              <input value={form.name} onChange={(e) => update("name", e.target.value)} required className={inputCls} />
            </div>
            <div>
              <label className={labelCls}>Slug *</label>
              <input value={form.slug} onChange={(e) => update("slug", e.target.value)} required className={inputCls} />
            </div>
            <div>
              <label className={labelCls}>SKU</label>
              <input value={form.sku} onChange={(e) => update("sku", e.target.value)} className={inputCls} />
            </div>
            <div>
              <label className={labelCls}>Category *</label>
              <select value={form.categoryId} onChange={(e) => update("categoryId", e.target.value)} required className={inputCls}>
                <option value="">Select category</option>
                {categories.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
              </select>
            </div>
            <div>
              <label className={labelCls}>Brand *</label>
              <select value={form.brandId} onChange={(e) => update("brandId", e.target.value)} required className={inputCls}>
                <option value="">Select brand</option>
                {brands.map((b) => <option key={b.id} value={b.id}>{b.name}</option>)}
              </select>
            </div>
            <div>
              <label className={labelCls}>Condition</label>
              <select value={form.condition} onChange={(e) => update("condition", e.target.value)} className={inputCls}>
                {["Brand New","Refurbished","Ex-UK","Ex-UK Graded A"].map((c) => <option key={c}>{c}</option>)}
              </select>
            </div>
            <div>
              <label className={labelCls}>Status</label>
              <select value={form.status} onChange={(e) => update("status", e.target.value)} className={inputCls}>
                {["ACTIVE","INACTIVE","OUT_OF_STOCK"].map((s) => <option key={s}>{s}</option>)}
              </select>
            </div>
            <div className="sm:col-span-2">
              <label className={labelCls}>Short Description</label>
              <input value={form.shortDesc} onChange={(e) => update("shortDesc", e.target.value)} className={inputCls} placeholder="One-line summary" />
            </div>
            <div className="sm:col-span-2">
              <label className={labelCls}>Description *</label>
              <textarea value={form.description} onChange={(e) => update("description", e.target.value)} required rows={4} className={`${inputCls} resize-none`} />
            </div>
          </div>
        </div>

        <div className="bg-white rounded-2xl border border-slate-100 p-6">
          <h2 className="font-black text-slate-800 mb-4">Pricing & Stock</h2>
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
            {[
              { k: "price", label: "Price (KES) *", required: true },
              { k: "comparePrice", label: "Compare Price", required: false },
              { k: "costPrice", label: "Cost Price", required: false },
              { k: "stock", label: "Stock *", required: true, type: "number" },
            ].map(({ k, label, required, type }) => (
              <div key={k}>
                <label className={labelCls}>{label}</label>
                <input type={type || "number"} step="0.01" value={form[k as keyof typeof form] as string}
                  onChange={(e) => update(k, e.target.value)} required={required} className={inputCls} placeholder="0" />
              </div>
            ))}
          </div>
        </div>

        {/* Images with upload */}
        <div className="bg-white rounded-2xl border border-slate-100 p-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="font-black text-slate-800">Product Images</h2>
            <button type="button" onClick={() => setImages([...images, ""])}
              className="flex items-center gap-1 text-sky-600 text-sm font-bold hover:text-sky-700">
              <Plus className="w-4 h-4" /> Add Image
            </button>
          </div>
          <div className="space-y-3">
            {images.map((img, i) => (
              <div key={i} className="flex gap-2 items-start">
                <div className="w-14 h-12 rounded-lg border border-slate-200 overflow-hidden bg-slate-50 flex-shrink-0">
                  {img ? (
                    <img src={img} alt="" className="w-full h-full object-cover" onError={(e) => { (e.target as HTMLImageElement).style.display = "none"; }} />
                  ) : (
                    <div className="w-full h-full flex items-center justify-center text-slate-300 text-xs">img</div>
                  )}
                </div>
                <div className="flex-1 flex gap-2">
                  <input value={img} onChange={(e) => { const arr = [...images]; arr[i] = e.target.value; setImages(arr); }}
                    className={`${inputCls} flex-1`} placeholder="https://example.com/image.jpg or upload →" />
                  <input
                    type="file" accept="image/*" className="hidden"
                    ref={(el) => { fileInputRefs.current[i] = el; }}
                    onChange={(e) => { const f = e.target.files?.[0]; if (f) handleFileUpload(f, i); e.target.value = ""; }}
                  />
                  <button type="button"
                    onClick={() => fileInputRefs.current[i]?.click()}
                    disabled={uploadingIdx === i}
                    className="flex items-center gap-1 px-3 py-2.5 rounded-xl border-2 border-sky-200 text-sky-600 hover:bg-sky-50 text-xs font-bold transition-colors disabled:opacity-50 flex-shrink-0">
                    {uploadingIdx === i ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Upload className="w-3.5 h-3.5" />}
                    <span className="hidden sm:inline">{uploadingIdx === i ? "..." : "Upload"}</span>
                  </button>
                </div>
                {images.length > 1 && (
                  <button type="button" onClick={() => setImages(images.filter((_, j) => j !== i))}
                    className="p-2.5 rounded-xl border border-red-200 text-red-500 hover:bg-red-50 transition-colors flex-shrink-0">
                    <X className="w-4 h-4" />
                  </button>
                )}
              </div>
            ))}
          </div>
          <p className="text-xs text-slate-400 mt-3">Paste an image URL or click Upload to select a file (max 5MB).</p>
        </div>

        <div className="bg-white rounded-2xl border border-slate-100 p-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="font-black text-slate-800">Specifications</h2>
            <button type="button" onClick={() => setSpecs([...specs, { label: "", value: "" }])} className="flex items-center gap-1 text-sky-600 text-sm font-bold">
              <Plus className="w-4 h-4" /> Add
            </button>
          </div>
          <div className="space-y-2">
            {specs.map((spec, i) => (
              <div key={i} className="flex gap-2">
                <input value={spec.label} onChange={(e) => { const arr = [...specs]; arr[i].label = e.target.value; setSpecs(arr); }} className={`${inputCls} flex-1`} placeholder="Processor" />
                <input value={spec.value} onChange={(e) => { const arr = [...specs]; arr[i].value = e.target.value; setSpecs(arr); }} className={`${inputCls} flex-1`} placeholder="Intel Core i7" />
                {specs.length > 1 && (
                  <button type="button" onClick={() => setSpecs(specs.filter((_, j) => j !== i))} className="p-2.5 rounded-xl border border-red-200 text-red-500 hover:bg-red-50">
                    <Trash2 className="w-4 h-4" />
                  </button>
                )}
              </div>
            ))}
          </div>
        </div>

        <div className="bg-white rounded-2xl border border-slate-100 p-6">
          <h2 className="font-black text-slate-800 mb-4">Tags & Flags</h2>
          <div className="mb-4">
            <label className={labelCls}>Tags (comma-separated)</label>
            <input value={tags} onChange={(e) => setTags(e.target.value)} className={inputCls} placeholder="gaming, student, iphone-16" />
          </div>
          <div className="flex gap-6">
            {[{ k: "featured", l: "Featured" }, { k: "isNew", l: "New" }, { k: "isHot", l: "Hot" }].map(({ k, l }) => (
              <label key={k} className="flex items-center gap-2 cursor-pointer">
                <input type="checkbox" checked={form[k as keyof typeof form] as boolean} onChange={(e) => update(k, e.target.checked)} className="w-4 h-4 rounded" />
                <span className="text-sm font-medium text-slate-700">{l}</span>
              </label>
            ))}
          </div>
        </div>

        <div className="flex gap-3">
          <button type="submit" disabled={loading} className="flex items-center gap-2 bg-sky-500 text-white px-8 py-3 rounded-xl font-bold hover:bg-sky-600 disabled:opacity-50">
            {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
            {loading ? "Saving..." : "Save Changes"}
          </button>
          <Link href="/admin/products" className="px-8 py-3 rounded-xl border-2 border-slate-200 text-slate-600 font-bold hover:bg-slate-50">Cancel</Link>
        </div>
      </form>
    </div>
  );
}
