"use client";

import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import Link from "next/link";
import Navbar from "@/components/Navbar";

type Product = {
  _id: string;
  title?: string;
  price?: number;
  cost?: number;
  qty?: number;
  stock?: number;
  scat?: string;
  cat?: string;
  category?: string;
  description?: string;
  shortDescription?: string;
  fullDescription?: string;
  images?: string[];
  photoUrl?: string;
  featured?: boolean;
};

export default function AdminEditProductPage() {
  const { id } = useParams();
  const router = useRouter();

  const [product, setProduct] = useState<Product | null>(null);
  const [collection, setCollection] = useState<"products" | "ecommers">("products");
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchProduct = async () => {
      setError(null);
      try {
        // Try ecommers first
        let res = await fetch(`/api/ecommers/${id}`);
        if (res.ok) {
          const data = await res.json();
          setProduct(data);
          setCollection("ecommers");
          return;
        }
        // Fallback to products
        res = await fetch(`/api/products/${id}`);
        if (!res.ok) throw new Error("Product not found");
        const data = await res.json();
        setProduct(data);
        setCollection("products");
      } catch (e: any) {
        setError(e.message || "Failed to load product");
      }
    };
    if (id) fetchProduct();
  }, [id]);

  const updateField = (field: keyof Product, value: any) => {
    if (!product) return;
    setProduct({ ...product, [field]: value });
  };

  const handleRemoveBg = async (imgUrl: string, index: number) => {
    try {
      const res = await fetch("/api/admin/remove-bg", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ imageUrl: imgUrl }),
      });
      const data = await res.json();
      if (!res.ok || !data?.dataUrl) throw new Error(data.error || "Failed to remove background");

      const nextImages = [...(product?.images || [])];
      nextImages[index] = data.dataUrl; // Replace with processed image (data URL)
      updateField("images", nextImages);
    } catch (e: any) {
      alert(e.message || "Background removal failed");
    }
  };

  // Local/offline background removal (no API) using @imgly/background-removal
  const handleRemoveBgLocal = async (imgUrl: string, index: number) => {
    try {
      // Lazy-load the library from CDN to avoid installing a package
      const libUrl = "https://cdn.skypack.dev/@imgly/background-removal";
      // @ts-ignore - webpackIgnore allows runtime import from external URL
      const mod: any = await import(/* webpackIgnore: true */ libUrl);
      const removeBackground = mod.removeBackground || mod.default || mod;

      // Load the image as a Blob to avoid CORS issues
      const imgResponse = await fetch(imgUrl, { mode: "cors" }).catch(() => null);
      if (!imgResponse || !imgResponse.ok) {
        throw new Error("Could not download image for local processing. Try the server Remove BG option.");
      }
      const imgBlob = await imgResponse.blob();

      // Process in-browser (downloads the ML model once and caches in the browser)
      const outputBlob = await removeBackground(imgBlob, {
        output: "blob",
        format: "image/png",
      });

      const dataUrl = await new Promise<string>((resolve) => {
        const reader = new FileReader();
        reader.onloadend = () => resolve(reader.result as string);
        reader.readAsDataURL(outputBlob);
      });

      const nextImages = [...(product?.images || [])];
      nextImages[index] = dataUrl;
      updateField("images", nextImages);
    } catch (e: any) {
      alert(e.message || "Local background removal failed");
    }
  };

  const handleDeleteImage = (index: number) => {
    const nextImages = [...(product?.images || [])];
    nextImages.splice(index, 1);
    updateField("images", nextImages);
  };

  const handleSave = async () => {
    if (!product) return;
    setSaving(true);
    setError(null);
    try {
      const payload: any = {
        title: product.title,
        price: product.price,
        cost: product.cost,
        qty: product.qty,
        stock: product.stock,
        description: product.description,
        shortDescription: product.shortDescription,
        fullDescription: product.fullDescription,
        scat: product.scat || product.category || product.cat,
        category: product.scat || product.category || product.cat,
        images: product.images,
        photoUrl: product.photoUrl,
        featured: product.featured,
      };

      const res = await fetch(`/api/${collection}/${product._id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      if (!res.ok) {
        const er = await res.json();
        throw new Error(er.error || "Failed to save product");
      }
      alert("Product saved");
      router.push("/admin/products");
    } catch (e: any) {
      setError(e.message || "Save failed");
    } finally {
      setSaving(false);
    }
  };

  if (error) {
    return (
      <div className="min-h-screen bg-gray-50">
        <Navbar />
        <div className="container mx-auto px-4 py-8">
          <p className="text-red-600">{error}</p>
          <Link href="/admin/products" className="text-blue-600 underline">Back</Link>
        </div>
      </div>
    );
  }

  if (!product) {
    return (
      <div className="min-h-screen bg-gray-50">
        <Navbar />
        <div className="container mx-auto px-4 py-8">Loading...</div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <Navbar />
      <div className="container mx-auto px-4 py-8">
        <div className="flex items-center justify-between mb-6">
          <h1 className="text-2xl font-bold text-gray-900">Edit Product</h1>
          <Link href="/admin/products" className="px-4 py-2 bg-gray-200 rounded">Back</Link>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Left: fields */}
          <div className="lg:col-span-2 space-y-4">
            <div className="bg-white rounded-lg shadow p-6 space-y-4">
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-1">Title</label>
                <input
                  type="text"
                  value={product.title || ""}
                  onChange={(e) => updateField("title", e.target.value)}
                  className="w-full px-4 py-2 border rounded"
                />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-1">Price</label>
                  <input type="number" value={product.price || 0} onChange={(e)=>updateField("price", parseFloat(e.target.value))} className="w-full px-4 py-2 border rounded" />
                </div>
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-1">Cost</label>
                  <input type="number" value={product.cost || 0} onChange={(e)=>updateField("cost", parseFloat(e.target.value))} className="w-full px-4 py-2 border rounded" />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-1">Stock</label>
                  <input type="number" value={product.stock || 0} onChange={(e)=>updateField("stock", parseInt(e.target.value))} className="w-full px-4 py-2 border rounded" />
                </div>
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-1">Qty</label>
                  <input type="number" value={product.qty || 0} onChange={(e)=>updateField("qty", parseInt(e.target.value))} className="w-full px-4 py-2 border rounded" />
                </div>
              </div>
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-1">Category</label>
                <input type="text" value={product.scat || product.category || product.cat || ""} onChange={(e)=>updateField("scat", e.target.value)} className="w-full px-4 py-2 border rounded" />
              </div>
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-1">Short Description</label>
                <textarea value={product.shortDescription || ""} onChange={(e)=>updateField("shortDescription", e.target.value)} className="w-full px-4 py-2 border rounded" rows={3} />
              </div>
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-1">Full Description</label>
                <textarea value={product.fullDescription || product.description || ""} onChange={(e)=>updateField("fullDescription", e.target.value)} className="w-full px-4 py-2 border rounded" rows={5} />
              </div>
            </div>
          </div>

          {/* Right: images */}
          <div>
            <div className="bg-white rounded-lg shadow p-6">
              <h2 className="text-lg font-semibold mb-3">Images</h2>
              <div className="grid grid-cols-2 gap-3">
                {(product.images && product.images.length > 0 ? product.images : product.photoUrl ? [product.photoUrl] : []).map((img, idx) => (
                  <div key={idx} className="border rounded overflow-hidden bg-gray-50">
                    <div className="aspect-square flex items-center justify-center">
                      <img src={img} alt="img" className="max-w-full max-h-full object-contain" />
                    </div>
                    <div className="flex gap-2 p-2">
                      <button
                        onClick={() => handleRemoveBg(img, idx)}
                        className="px-2 py-1 bg-blue-600 text-white text-xs rounded"
                      >
                        Remove BG
                      </button>
                      <button
                        onClick={() => handleRemoveBgLocal(img, idx)}
                        className="px-2 py-1 bg-emerald-600 text-white text-xs rounded"
                      >
                        Remove BG (Local)
                      </button>
                      <button
                        onClick={() => handleDeleteImage(idx)}
                        className="px-2 py-1 bg-red-600 text-white text-xs rounded"
                      >
                        Delete
                      </button>
                    </div>
                  </div>
                ))}
              </div>
              <div className="mt-3">
                <label className="block text-sm font-semibold text-gray-700 mb-1">Main Image URL</label>
                <input type="text" value={product.photoUrl || ""} onChange={(e)=>updateField("photoUrl", e.target.value)} className="w-full px-3 py-2 border rounded" />
              </div>
            </div>
          </div>
        </div>

        <div className="mt-6 flex justify-end gap-3">
          <button onClick={()=>router.push("/admin/products")} className="px-6 py-2 bg-gray-200 rounded">Cancel</button>
          <button onClick={handleSave} disabled={saving} className="px-6 py-2 bg-purple-600 text-white rounded disabled:opacity-50">
            {saving ? "Saving..." : "Save Changes"}
          </button>
        </div>
      </div>
    </div>
  );
}
