"use client";

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

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

export default function NewProductPage() {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  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: true, isHot: false, status: "ACTIVE",
  });

  useEffect(() => {
    Promise.all([
      fetch("/api/admin/categories").then((r) => r.json()),
      fetch("/api/admin/brands").then((r) => r.json()),
    ]).then(([cats, brds]) => { setCategories(cats); setBrands(brds); });
  }, []);

  const slugify = (s: string) => s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");

  const update = (k: string, v: string | boolean) => {
    setForm((f) => {
      const next = { ...f, [k]: v };
      if (k === "name" && typeof v === "string") next.slug = slugify(v);
      return next;
    });
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    try {
      const res = await fetch("/api/admin/products", {
        method: "POST",
        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 created!");
      router.push("/admin/products");
    } catch (err) {
      toast.error((err as Error).message || "Failed to create product");
    } finally {
      setLoading(false);
    }
  };

  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 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";

  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 transition-colors">
          <ArrowLeft className="w-4 h-4 text-slate-600" />
        </Link>
        <div>
          <h1 className="text-2xl font-black text-slate-900">Add New Product</h1>
          <p className="text-slate-500 text-sm">Fill in all required fields</p>
        </div>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Basic info */}
        <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} placeholder="e.g. Dell XPS 15 Core i7 32GB 1TB" />
            </div>
            <div>
              <label className={labelCls}>Slug *</label>
              <input value={form.slug} onChange={(e) => update("slug", slugify(e.target.value))} required className={inputCls} placeholder="auto-generated" />
            </div>
            <div>
              <label className={labelCls}>SKU</label>
              <input value={form.sku} onChange={(e) => update("sku", e.target.value)} className={inputCls} placeholder="PT-001" />
            </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 product summary" />
            </div>
            <div className="sm:col-span-2">
              <label className={labelCls}>Full Description *</label>
              <textarea value={form.description} onChange={(e) => update("description", e.target.value)} required rows={4}
                className={`${inputCls} resize-none`} placeholder="Detailed product description..." />
            </div>
          </div>
        </div>

        {/* Pricing */}
        <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: "Selling Price (KES) *", required: true },
              { k: "comparePrice", label: "Compare Price (KES)", required: false },
              { k: "costPrice", label: "Cost Price (KES)", required: false },
              { k: "stock", label: "Stock Quantity *", 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 */}
        <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">
                {/* Preview */}
                <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, JPEG/PNG/WebP).</p>
        </div>

        {/* Specs */}
        <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 hover:text-sky-700">
              <Plus className="w-4 h-4" /> Add Spec
            </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-12th Gen" />
                {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 transition-colors">
                    <Trash2 className="w-4 h-4" />
                  </button>
                )}
              </div>
            ))}
          </div>
        </div>

        {/* Tags & Flags */}
        <div className="bg-white rounded-2xl border border-slate-100 p-6">
          <h2 className="font-black text-slate-800 mb-4">Tags & Visibility</h2>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div className="sm:col-span-2">
              <label className={labelCls}>Tags (comma-separated)</label>
              <input value={tags} onChange={(e) => setTags(e.target.value)} className={inputCls} placeholder="gaming, student, business, iphone-16" />
            </div>
            <div className="flex flex-col gap-3">
              {[
                { k: "featured", label: "Featured Product" },
                { k: "isNew", label: "Mark as New" },
                { k: "isHot", label: "Mark as Hot" },
              ].map(({ k, label }) => (
                <label key={k} className="flex items-center gap-3 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 border-slate-300 text-sky-500 focus:ring-sky-400" />
                  <span className="text-sm font-medium text-slate-700">{label}</span>
                </label>
              ))}
            </div>
          </div>
        </div>

        {/* Submit */}
        <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 transition-colors disabled:opacity-50">
            {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
            {loading ? "Creating..." : "Create Product"}
          </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 transition-colors">
            Cancel
          </Link>
        </div>
      </form>
    </div>
  );
}
