"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";

type ProductImage = {
  file: File;
  preview: string;
  base64?: string;
  thumb?: string; // thumbnail base64
};

type Variation = {
  colorName: string;
  colorCode: string;
  price?: string; // string in form, convert later
  stock?: string;
  images: ProductImage[];
};

// create a thumbnail (base64 in JPEG) from a base64 or Blob
async function createThumbnailFromBase64(base64: string, maxSize = 320): Promise<string> {
  return new Promise((resolve) => {
    const img = new Image();
    img.crossOrigin = "anonymous";
    img.onload = () => {
      const ratio = Math.min(maxSize / img.width, maxSize / img.height, 1);
      const w = Math.max(1, Math.round(img.width * ratio));
      const h = Math.max(1, Math.round(img.height * ratio));
      const canvas = document.createElement("canvas");
      canvas.width = w;
      canvas.height = h;
      const ctx = canvas.getContext("2d");
      if (ctx) {
        ctx.clearRect(0, 0, w, h);
        ctx.drawImage(img, 0, 0, w, h);
        const out = canvas.toDataURL("image/jpeg", 0.8);
        resolve(out);
      } else {
        resolve(base64);
      }
    };
    img.onerror = () => resolve(base64);
    img.src = base64;
  });
}

export default function AdminAddProductPage() {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [images, setImages] = useState<ProductImage[]>([]);
  const [variations, setVariations] = useState<Variation[]>([]);
  const [formData, setFormData] = useState({
    title: "",
    itc1: "",
    itn: "",
    sku: "",
    bcode1: "",
    description: "",
    shortDescription: "",
    fullDescription: "",
    productDetails: "",
    qty: "",
    stock: "",
    cost: "",
    price: "",
    supplier: "",
    rack: "",
    lastSell: "",
    newCost: "",
    category: "",
    scat: "",
    cat: "",
    itc: "",
    mfg: "",
    vat: "",
    unit: "",
  });

  // Handle image upload
  const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files || []);
    if (files.length === 0) return;

    files.forEach((file) => {
      if (file.type.startsWith("image/")) {
        const reader = new FileReader();
        reader.onloadend = async () => {
          const base64 = reader.result as string;
          const thumb = await createThumbnailFromBase64(base64);
          setImages((prev) => [
            ...prev,
            {
              file,
              preview: URL.createObjectURL(file),
              base64,
              thumb,
            },
          ]);
        };
        reader.readAsDataURL(file);
      }
    });
  };

  // Handle variation image upload
  const handleVariationImageUpload = (index: number, e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files || []);
    if (files.length === 0) return;

    const newVars = [...variations];
    files.forEach((file) => {
      if (!file.type.startsWith("image/")) return;
      const reader = new FileReader();
      reader.onloadend = async () => {
        const base64 = reader.result as string;
        const thumb = await createThumbnailFromBase64(base64);
        newVars[index].images.push({ file, preview: URL.createObjectURL(file), base64, thumb });
        setVariations(newVars.map((v) => ({ ...v })));
      };
      reader.readAsDataURL(file);
    });
  };

  const removeVariationImage = (vIdx: number, imgIdx: number) => {
    const newVars = [...variations];
    const p = newVars[vIdx].images[imgIdx];
    URL.revokeObjectURL(p.preview);
    newVars[vIdx].images.splice(imgIdx, 1);
    setVariations(newVars);
  };

  // Remove image
  const removeImage = (index: number) => {
    setImages((prev) => {
      const newImages = prev.filter((_, i) => i !== index);
      URL.revokeObjectURL(prev[index].preview);
      return newImages;
    });
  };

  // Convert images to base64 array
  const getImageBase64Array = () => {
    return images.map((img) => img.base64 || "").filter(Boolean);
  };
  const getImageThumbArray = () => {
    return images.map((img) => img.thumb || img.base64 || "").filter(Boolean);
  };

  const variationsDto = () =>
    variations.map((v) => ({
      colorName: v.colorName,
      colorCode: v.colorCode,
      price: v.price ? parseFloat(v.price) : undefined,
      stock: v.stock ? parseInt(v.stock) : undefined,
      images: v.images.map((i) => i.base64).filter(Boolean),
      thumbnails: v.images.map((i) => i.thumb || i.base64).filter(Boolean),
    }));

  // Handle form submit
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);

    try {
      const productData = {
        ...formData,
        qty: formData.qty ? parseFloat(formData.qty) : 0,
        stock: formData.stock ? parseFloat(formData.stock) : 0,
        cost: formData.cost ? parseFloat(formData.cost) : 0,
        price: formData.price ? parseFloat(formData.price) : 0,
        lastSell: formData.lastSell ? parseFloat(formData.lastSell) : 0,
        newCost: formData.newCost ? parseFloat(formData.newCost) : 0,
        vat: formData.vat ? parseFloat(formData.vat) : 0,
        images: getImageBase64Array(),
        thumbnails: getImageThumbArray(),
        photoUrl: images[0]?.base64 || "",
        photoThumb: getImageThumbArray()[0] || "",
        variations: variationsDto(),
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
        active: true,
      };

      const response = await fetch("/api/ecommers", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(productData),
      });

      const result = await response.json();

      if (!response.ok) {
        throw new Error(result.error || "Failed to create product");
      }

      alert("Product added successfully!");
      router.push("/admin/products");
    } catch (error) {
      console.error("Error adding product:", error);
      alert(error instanceof Error ? error.message : "Failed to add product");
    } finally {
      setLoading(false);
    }
  };

  // Handle input change
  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>
  ) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  };

  const addVariation = () => setVariations((v) => [...v, { colorName: "", colorCode: "#000000", price: "", stock: "", images: [] }]);
  const removeVariation = (idx: number) => setVariations((v) => v.filter((_, i) => i !== idx));
  const updateVariation = (idx: number, key: keyof Variation, value: any) => {
    const copy = [...variations];
    (copy[idx] as any)[key] = value;
    setVariations(copy);
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold text-gray-900">Add New Product</h1>
        <p className="text-gray-600 mt-2">Add a new product to the e-commerce catalog</p>
      </div>

      <form onSubmit={handleSubmit} className="bg-white rounded-lg shadow p-6 space-y-6">
        {/* Basic Information */}
        <div className="border-b pb-4">
          <h2 className="text-xl font-semibold text-gray-900 mb-4">Basic Information</h2>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-1">
                Product Title *
              </label>
              <input
                type="text"
                name="title"
                value={formData.title}
                onChange={handleChange}
                required
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
                placeholder="Enter product title"
              />
            </div>
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-1">SKU *</label>
              <input
                type="text"
                name="sku"
                value={formData.sku}
                onChange={handleChange}
                required
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
                placeholder="Enter SKU"
              />
            </div>
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-1">Category (SCAT) *</label>
              <input
                type="text"
                name="scat"
                value={formData.scat}
                onChange={handleChange}
                required
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
                placeholder="Enter category"
              />
            </div>
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-1">Price *</label>
              <input
                type="number"
                step="0.01"
                name="price"
                value={formData.price}
                onChange={handleChange}
                required
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
                placeholder="0.00"
              />
            </div>
          </div>
          <div className="mt-4 space-y-4">
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-1">
                Short Description
              </label>
              <textarea
                name="shortDescription"
                value={formData.shortDescription}
                onChange={handleChange}
                rows={2}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
                placeholder="Enter short description"
              />
            </div>
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-1">
                Full Description
              </label>
              <textarea
                name="fullDescription"
                value={formData.fullDescription}
                onChange={handleChange}
                rows={5}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
                placeholder="Enter full detailed description"
              />
            </div>
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-1">
                Product Details (JSON)
              </label>
              <textarea
                name="productDetails"
                value={formData.productDetails}
                onChange={handleChange}
                rows={4}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 font-mono text-sm"
                placeholder='{"color": "Red", "size": "Large"}'
              />
            </div>
          </div>
        </div>

        {/* Variations */}
        <div className="border-b pb-4">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-xl font-semibold text-gray-900">Color Variations</h2>
            <button type="button" onClick={addVariation} className="px-3 py-1.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded text-sm">+ Add Variation</button>
          </div>
          {variations.length === 0 && (
            <p className="text-sm text-gray-500">No variations added yet.</p>
          )}
          <div className="space-y-4">
            {variations.map((v, idx) => (
              <div key={idx} className="border rounded p-4">
                <div className="grid grid-cols-1 md:grid-cols-4 gap-3">
                  <div>
                    <label className="block text-sm font-semibold text-gray-700 mb-1">Color Name</label>
                    <input type="text" value={v.colorName} onChange={(e)=>updateVariation(idx, 'colorName', e.target.value)} className="w-full px-3 py-2 border rounded" placeholder="e.g., Black" />
                  </div>
                  <div>
                    <label className="block text-sm font-semibold text-gray-700 mb-1">Color Code</label>
                    <input type="color" value={v.colorCode} onChange={(e)=>updateVariation(idx, 'colorCode', e.target.value)} className="w-12 h-10 p-0 border rounded" />
                  </div>
                  <div>
                    <label className="block text-sm font-semibold text-gray-700 mb-1">Price (override)</label>
                    <input type="number" step="0.01" value={v.price || ''} onChange={(e)=>updateVariation(idx, 'price', e.target.value)} className="w-full px-3 py-2 border rounded" placeholder="Leave empty to use main price" />
                  </div>
                  <div>
                    <label className="block text-sm font-semibold text-gray-700 mb-1">Stock</label>
                    <input type="number" value={v.stock || ''} onChange={(e)=>updateVariation(idx, 'stock', e.target.value)} className="w-full px-3 py-2 border rounded" />
                  </div>
                </div>
                <div className="mt-3">
                  <label className="block text-sm font-semibold text-gray-700 mb-1">Variation Images</label>
                  <input type="file" accept="image/*" multiple onChange={(e)=>handleVariationImageUpload(idx, e)} className="w-full px-3 py-2 border rounded" />
                  {v.images.length > 0 && (
                    <div className="grid grid-cols-4 gap-3 mt-3">
                      {v.images.map((img, ii) => (
                        <div key={ii} className="relative">
                          <img src={img.preview} className="w-full h-24 object-cover rounded border" />
                          <button type="button" onClick={()=>removeVariationImage(idx, ii)} className="absolute top-1 right-1 bg-red-500 text-white rounded-full p-1">×</button>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
                <div className="mt-3 text-right">
                  <button type="button" onClick={()=>removeVariation(idx)} className="px-3 py-1.5 bg-red-600 text-white rounded text-sm">Remove Variation</button>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Images Upload */}
        <div className="border-b pb-4">
          <h2 className="text-xl font-semibold text-gray-900 mb-4">Product Images</h2>
          <div>
            <input
              type="file"
              accept="image/*"
              multiple
              onChange={handleImageUpload}
              className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
            />
          </div>
          {images.length > 0 && (
            <div className="grid grid-cols-4 gap-4 mt-4">
              {images.map((image, index) => (
                <div key={index} className="relative">
                  <img
                    src={image.preview}
                    alt={`Preview ${index + 1}`}
                    className="w-full h-32 object-cover rounded border"
                  />
                  <button
                    type="button"
                    onClick={() => removeImage(index)}
                    className="absolute top-1 right-1 bg-red-500 text-white rounded-full p-1"
                  >
                    ×
                  </button>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Submit */}
        <div className="flex gap-4 justify-end">
          <Link
            href="/admin/products"
            className="px-6 py-2 bg-gray-200 hover:bg-gray-300 text-gray-700 font-semibold rounded-lg transition"
          >
            Cancel
          </Link>
          <button
            type="submit"
            disabled={loading}
            className="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-lg transition disabled:opacity-50"
          >
            {loading ? "Adding..." : "Add Product"}
          </button>
        </div>
      </form>
    </div>
  );
}

