import React, { useState } from "react";
import axios from "axios";
import { motion } from "framer-motion";
import { useGetCategoryTreeQuery } from "../../features/categories/categoryAPI";
import { flattenCategories } from "../../utils/flattenCategories";

const ProductAdd = () => {
  const [formData, setFormData] = useState({
    name: "",
    slug: "",
    description: "",
    category: "",
    tags: "",
    basePrice: "",
    hasVariants: false,
    metaKeywords: "",
    status: "active",
    isFeatured: false,
    isDigital: false,
    weightValue: "",
    weightUnit: "g",
    length: "",
    width: "",
    height: "",
    dimensionUnit: "cm",
  });

  const [previewImages, setPreviewImages] = useState([]);

  const [primaryImage, setPrimaryImage] = useState(null);
  const [primaryPreview, setPrimaryPreview] = useState(null);

  const [galleryFiles, setGalleryFiles] = useState([]);
  const [galleryPreviews, setGalleryPreviews] = useState([]);

  const [variants, setVariants] = useState([
    {
      color: "",
      price: "",
      stock: "",
      primaryImage: null,
      galleryImages: [],
      primaryPreview: null,
      galleryPreviews: [],
    },
  ]);

  // ✅ Fetch categories
  const { data: categoryResponse, isLoading } = useGetCategoryTreeQuery();
  const categories = categoryResponse?.data || [];

  const flatCategories = flattenCategories(categories);

  console.log("Categories from API:", categories);
  console.log("Flattened categories:", flattenCategories(categories));

  // handle text/checkbox input
  const handleChange = (e) => {
    const { name, value, type, checked } = e.target;
    setFormData({
      ...formData,
      [name]: type === "checkbox" ? checked : value,
    });
  };
  console.log("Submitting category ID:", formData.category);

  // Primary Image
  const handlePrimaryImage = (e) => {
    const file = e.target.files[0];
    if (!file) return;

    setPrimaryImage(file);
    setPrimaryPreview(URL.createObjectURL(file));
  };

  // Gallery Images (MAX 5)
  const handleGalleryImages = (e) => {
    const files = Array.from(e.target.files).slice(0, 5);

    setGalleryFiles(files);
    setGalleryPreviews(files.map((file) => URL.createObjectURL(file)));
  };

  const addVariant = () => {
    setVariants([
      ...variants,
      {
        color: "",
        price: "",
        stock: "",
        primaryImage: null,
        galleryImages: [],
      },
    ]);
  };

  const updateVariant = (index, field, value) => {
    const updated = [...variants];
    updated[index][field] = value;
    setVariants(updated);
  };

  const handleVariantPrimary = (index, e) => {
    const file = e.target.files[0];
    if (!file) return;

    const updated = [...variants];
    updated[index].primaryImage = file;
    updated[index].primaryPreview = URL.createObjectURL(file);
    setVariants(updated);
  };

  const handleVariantGallery = (index, e) => {
    const files = Array.from(e.target.files).slice(0, 5);
    const updated = [...variants];
    updated[index].galleryImages = files;
    updated[index].galleryPreviews = files.map((f) => URL.createObjectURL(f));
    setVariants(updated);
  };

  const removeGalleryImage = (index) => {
    setGalleryFiles((prev) => prev.filter((_, i) => i !== index));
    setGalleryPreviews((prev) => prev.filter((_, i) => i !== index));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    try {
      const token = localStorage.getItem("token");
      const form = new FormData();

      // ======================
      // VALIDATION
      // ======================
      // if (!formData.name || !formData.slug) {
      //   alert("❌ Name and slug are required");
      //   return;
      // }

      // ======================
      // BASIC FIELDS
      // ======================
      form.append("name", formData.name);
      form.append("slug", formData.slug);
      form.append("description", formData.description || "");

      // Only append category if it's not empty
      if (formData.category) {
        form.append("category", formData.category);
      }

      // Convert basePrice to number and validate
      const basePrice = Number(formData.basePrice);
      if (!isNaN(basePrice) && basePrice > 0) {
        form.append("basePrice", basePrice);
      } else {
        alert("❌ Valid base price is required");
        return;
      }

      form.append("status", formData.status);

      form.append("hasVariants", formData.hasVariants);
      form.append("isFeatured", formData.isFeatured);
      form.append("isDigital", formData.isDigital);

      // ======================
      // ARRAYS
      // ======================
      const tags = formData.tags
        .split(",")
        .map((t) => t.trim())
        .filter(Boolean);

      if (tags.length > 0) {
        tags.forEach((tag) => form.append("tags[]", tag));
      }

      const keywords = formData.metaKeywords
        .split(",")
        .map((k) => k.trim())
        .filter(Boolean);

      if (keywords.length > 0) {
        keywords.forEach((k) => form.append("metaKeywords[]", k));
      }

      // ======================
      // WEIGHT & DIMENSIONS
      // ======================
      if (formData.weightValue) {
        form.append("weight[value]", Number(formData.weightValue));
        form.append("weight[unit]", formData.weightUnit);
      }

      if (formData.length || formData.width || formData.height) {
        if (formData.length)
          form.append("dimensions[length]", Number(formData.length));
        if (formData.width)
          form.append("dimensions[width]", Number(formData.width));
        if (formData.height)
          form.append("dimensions[height]", Number(formData.height));
        form.append("dimensions[unit]", formData.dimensionUnit);
      }

      // ======================
      // VARIANTS MODE
      // ======================
      if (formData.hasVariants) {
        // Validate variants
        const validVariants = variants.filter(
          (v) => v.color && v.price && v.stock,
        );

        if (validVariants.length === 0) {
          alert("❌ Please add at least one complete variant");
          return;
        }

        // 🔥 SEND VARIANTS AS JSON
        const cleanVariants = validVariants.map((v) => ({
          size: "default",
          color: v.color,
          sku: `${formData.slug}-${v.color.toLowerCase().replace(/\s+/g, "-")}`,
          price: Number(v.price),
          compareAtPrice: null,
          inventory: {
            quantity: Number(v.stock),
            trackInventory: true,
          },
        }));

        form.append("variants", JSON.stringify(cleanVariants));

        // 🔥 VARIANT IMAGES
        // VARIANT IMAGES
        // 🔥 VARIANT IMAGES - Using color as field identifier
        validVariants.forEach((variant) => {
          const color = variant.color.trim();
          const fieldName = `variantImages_${color}`;

          console.log(`📤 Processing variant: ${color}`);
          console.log(`📤 Field name: ${fieldName}`);

          // Combine primary + gallery images
          const allImages = [];

          if (variant.primaryImage) {
            allImages.push(variant.primaryImage);
          }

          if (variant.galleryImages?.length) {
            allImages.push(...variant.galleryImages);
          }

          // Append all images with the color-based field name
          allImages.forEach((img) => {
            form.append(fieldName, img);
          });

          console.log(`✅ Sent ${allImages.length} images for ${color}`);
        });
      }

      // ======================
      // SIMPLE PRODUCT MODE
      // ======================
      else {
        if (primaryImage) {
          form.append("primaryImage", primaryImage);
        }

        galleryFiles.forEach((file) => {
          form.append("galleryImages", file);
        });
      }

      // ======================
      // DEBUG LOG
      // ======================
      console.log("📦 FormData contents:");
      for (let pair of form.entries()) {
        console.log(pair[0], ":", pair[1]);
      }

      // ======================
      // API CALL
      // ======================
      const response = await axios.post(
        "http://localhost:3000/api/admin/products",
        form,
        {
          headers: {
            Authorization: `Bearer ${token}`,
            "Content-Type": "multipart/form-data",
          },
        },
      );

      console.log("✅ Success:", response.data);
      alert("✅ Product created successfully!");

      // Reset form
      setFormData({
        name: "",
        slug: "",
        description: "",
        category: "",
        tags: "",
        basePrice: "",
        hasVariants: false,
        metaKeywords: "",
        status: "active",
        isFeatured: false,
        isDigital: false,
        weightValue: "",
        weightUnit: "g",
        length: "",
        width: "",
        height: "",
        dimensionUnit: "cm",
      });
      setPrimaryImage(null);
      setPrimaryPreview(null);
      setGalleryFiles([]);
      setGalleryPreviews([]);
      setVariants([
        {
          color: "",
          price: "",
          stock: "",
          primaryImage: null,
          galleryImages: [],
          primaryPreview: null,
          galleryPreviews: [],
        },
      ]);
    } catch (err) {
      console.error("❌ Error details:", err);

      if (err.response) {
        // Server responded with error
        console.error("Response data:", err.response.data);
        console.error("Response status:", err.response.status);
        console.error("Response headers:", err.response.headers);

        const errorMessage =
          err.response.data?.message ||
          err.response.data?.error ||
          JSON.stringify(err.response.data);

        alert(`❌ Server Error: ${errorMessage}`);
      } else if (err.request) {
        // Request made but no response
        console.error("No response received:", err.request);
        alert("❌ No response from server. Check if backend is running.");
      } else {
        // Error in request setup
        console.error("Error setting up request:", err.message);
        alert(`❌ Error: ${err.message}`);
      }
    }
  };

  return (
    <div className="min-h-screen bg-gray-50 py-10 px-6">
      <motion.div
        initial={{ opacity: 0, y: 30 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.4 }}
        className="max-w-7xl mx-auto bg-white rounded-2xl shadow-xl overflow-hidden border border-gray-200"
      >
        <div className="px-8 py-6 bg-gradient-to-r from-indigo-500 to-blue-500 text-white">
          <h2 className="text-3xl font-semibold">Add New Product</h2>
          <p className="text-sm text-indigo-100 mt-1">
            Fill in details below to create a new product listing.
          </p>
        </div>

        <form
          onSubmit={handleSubmit}
          className="grid grid-cols-1 md:grid-cols-2 gap-10 p-8"
        >
          {/* Left Side */}
          <div className="space-y-8">
            <div className="bg-white border rounded-xl shadow-sm p-6">
              <h3 className="text-xl font-semibold text-gray-800 mb-4 border-b pb-2">
                🧾 Basic Information
              </h3>
              <div className="space-y-4">
                <Input
                  label="Product Name *"
                  name="name"
                  value={formData.name}
                  onChange={handleChange}
                  placeholder="e.g. Elegant Silk Saree"
                  required
                />

                <div>
                  <label className="block font-medium text-gray-700">
                    Slug (auto)
                  </label>
                  <input
                    value={formData.name
                      .toLowerCase()
                      .replace(/[^a-z0-9]+/g, "-")
                      .replace(/(^-|-$)/g, "")}
                    disabled
                    className="mt-2 w-full bg-gray-100 border rounded-lg px-4 py-2"
                  />
                </div>

                <Textarea
                  label="Description"
                  name="description"
                  value={formData.description}
                  onChange={handleChange}
                  placeholder="Describe your product"
                />

                {/* ✅ Category Select */}
                <Select
                  label="Category"
                  name="category"
                  value={formData.category} // stores ID
                  onChange={handleChange}
                  options={
                    isLoading
                      ? [{ value: "", label: "Loading categories..." }]
                      : flatCategories
                  }
                />
              </div>
            </div>

            <div className="bg-white border rounded-xl shadow-sm p-6">
              <h3 className="text-xl font-semibold text-gray-800 mb-4 border-b pb-2">
                🏷️ Product Details
              </h3>
              <div className="space-y-4">
                <Input
                  label="Base Price (₹) *"
                  name="basePrice"
                  type="number"
                  value={formData.basePrice}
                  onChange={handleChange}
                  placeholder="2599"
                  required
                />

                <Input
                  label="Tags (comma separated)"
                  name="tags"
                  value={formData.tags}
                  onChange={handleChange}
                  placeholder="saree, silk, ethnic"
                />

                <Input
                  label="Meta Keywords"
                  name="metaKeywords"
                  value={formData.metaKeywords}
                  onChange={handleChange}
                  placeholder="wedding, women, fashion"
                />

                <div className="flex flex-wrap gap-4 pt-2">
                  {[
                    { name: "hasVariants", label: "Has Variants" },
                    { name: "isFeatured", label: "Featured" },
                    { name: "isDigital", label: "Digital" },
                  ].map((opt) => (
                    <label
                      key={opt.name}
                      className="flex items-center space-x-2 text-gray-700"
                    >
                      <input
                        type="checkbox"
                        name={opt.name}
                        checked={formData[opt.name]}
                        onChange={handleChange}
                      />
                      <span>{opt.label}</span>
                    </label>
                  ))}
                </div>
              </div>
            </div>

            {formData.hasVariants && (
              <div className="bg-white border rounded-xl shadow-sm p-6">
                <h3 className="text-xl font-semibold text-gray-800 mb-4 border-b pb-2">
                  🎨 Product Variants
                </h3>

                {variants.map((variant, index) => (
                  <div
                    key={index}
                    className="border-2 border-indigo-200 rounded-xl p-5 mb-6 space-y-4 bg-gradient-to-br from-white to-indigo-50"
                  >
                    <div className="flex items-center justify-between">
                      <h4 className="font-semibold text-indigo-600 text-lg">
                        🎨 Variant #{index + 1}
                      </h4>
                      {variants.length > 1 && (
                        <button
                          type="button"
                          onClick={() => {
                            setVariants(variants.filter((_, i) => i !== index));
                          }}
                          className="text-red-500 hover:text-red-700 text-sm font-medium"
                        >
                          🗑️ Remove
                        </button>
                      )}
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                      <Input
                        label="Color *"
                        value={variant.color}
                        onChange={(e) =>
                          updateVariant(index, "color", e.target.value)
                        }
                        placeholder="e.g. Red, Blue, Green"
                      />

                      <Input
                        label="Price (₹) *"
                        type="number"
                        value={variant.price}
                        onChange={(e) =>
                          updateVariant(index, "price", e.target.value)
                        }
                        placeholder="2599"
                      />

                      <Input
                        label="Stock Quantity *"
                        type="number"
                        value={variant.stock}
                        onChange={(e) =>
                          updateVariant(index, "stock", e.target.value)
                        }
                        placeholder="50"
                      />
                    </div>

                    {/* Variant Images */}
                    <div className="bg-white rounded-lg p-4 border border-indigo-100 space-y-4">
                      <h5 className="font-semibold text-gray-700 text-sm">
                        📸 Variant Images
                      </h5>

                      {/* Primary Image for Variant */}
                      <div>
                        <label className="block text-sm font-medium text-gray-600 mb-2">
                          Primary Image
                        </label>

                        <label className="flex flex-col items-center justify-center border-2 border-dashed border-gray-300 rounded-lg p-4 cursor-pointer hover:bg-gray-50 transition">
                          <input
                            type="file"
                            accept="image/*"
                            onChange={(e) => handleVariantPrimary(index, e)}
                            className="hidden"
                          />

                          {!variant.primaryPreview ? (
                            <>
                              <span className="text-gray-400 text-2xl">📷</span>
                              <p className="text-xs text-gray-500 mt-1">
                                Upload primary image
                              </p>
                            </>
                          ) : (
                            <div className="relative">
                              <img
                                src={variant.primaryPreview}
                                className="w-32 h-32 object-cover rounded border-2 border-indigo-300"
                                alt={`Variant ${index + 1} primary`}
                              />
                              <span className="absolute -top-2 -right-2 bg-indigo-600 text-white text-xs px-2 py-0.5 rounded-full">
                                Primary
                              </span>
                            </div>
                          )}
                        </label>
                      </div>

                      {/* Gallery Images for Variant */}
                      <div>
                        <label className="block text-sm font-medium text-gray-600 mb-2">
                          Gallery Images{" "}
                          <span className="text-xs text-gray-400">(Max 5)</span>
                        </label>

                        <label className="flex flex-col items-center justify-center border-2 border-dashed border-gray-300 rounded-lg p-4 cursor-pointer hover:bg-gray-50 transition">
                          <input
                            type="file"
                            multiple
                            accept="image/*"
                            onChange={(e) => handleVariantGallery(index, e)}
                            className="hidden"
                          />

                          <span className="text-gray-400 text-2xl">🖼️</span>
                          <p className="text-xs text-gray-500 mt-1">
                            Upload gallery images
                          </p>
                        </label>

                        {variant.galleryPreviews?.length > 0 && (
                          <div className="grid grid-cols-3 sm:grid-cols-4 gap-3 mt-3">
                            {variant.galleryPreviews.map((src, i) => (
                              <div
                                key={i}
                                className="relative group rounded border-2 border-gray-200 overflow-hidden"
                              >
                                <img
                                  src={src}
                                  className="w-full h-24 object-cover"
                                  alt={`Variant ${index + 1} gallery ${i + 1}`}
                                />
                                <button
                                  type="button"
                                  onClick={() => {
                                    const updated = [...variants];
                                    updated[index].galleryImages = updated[
                                      index
                                    ].galleryImages.filter(
                                      (_, idx) => idx !== i,
                                    );
                                    updated[index].galleryPreviews = updated[
                                      index
                                    ].galleryPreviews.filter(
                                      (_, idx) => idx !== i,
                                    );
                                    setVariants(updated);
                                  }}
                                  className="absolute top-1 right-1 bg-red-500 text-white text-xs rounded-full w-5 h-5 flex items-center justify-center opacity-0 group-hover:opacity-100 transition"
                                >
                                  ✕
                                </button>
                              </div>
                            ))}
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                ))}

                <button
                  type="button"
                  onClick={addVariant}
                  className="mt-4 bg-indigo-500 text-white px-4 py-2 rounded-lg hover:bg-indigo-600 transition"
                >
                  ➕ Add Another Variant
                </button>
              </div>
            )}
          </div>

          {/* Right Side */}
          <div className="space-y-8">
            {/* Weight & Dimensions */}
            <div className="bg-white border rounded-xl shadow-sm p-6">
              <h3 className="text-xl font-semibold text-gray-800 mb-4 border-b pb-2">
                📦 Weight & Dimensions
              </h3>
              <div className="grid grid-cols-2 gap-4">
                <Input
                  label="Weight"
                  name="weightValue"
                  type="number"
                  value={formData.weightValue}
                  onChange={handleChange}
                  placeholder="700"
                />
                <Select
                  label="Unit"
                  name="weightUnit"
                  value={formData.weightUnit}
                  onChange={handleChange}
                  options={[
                    { value: "g", label: "g" },
                    { value: "kg", label: "kg" },
                  ]}
                />
              </div>

              <div className="grid grid-cols-3 gap-3 mt-4">
                {["length", "width", "height"].map((dim) => (
                  <Input
                    key={dim}
                    label={dim.charAt(0).toUpperCase() + dim.slice(1)}
                    name={dim}
                    type="number"
                    value={formData[dim]}
                    onChange={handleChange}
                    placeholder="10"
                  />
                ))}
              </div>
            </div>

            {/* Image Upload Section */}
            <div className="bg-white border rounded-xl shadow-sm p-6 space-y-8">
              <h3 className="text-xl font-semibold text-gray-800 border-b pb-2">
                🖼️ Product Images
              </h3>

              {!formData.hasVariants ? (
                <>
                  {/* Simple Product Images */}
                  {/* Primary Image */}
                  <div>
                    <label className="block font-medium text-gray-700 mb-3">
                      Primary Image
                    </label>

                    <label className="flex flex-col items-center justify-center border-2 border-dashed rounded-xl p-6 cursor-pointer hover:bg-indigo-50 transition">
                      <input
                        type="file"
                        accept="image/*"
                        onChange={handlePrimaryImage}
                        className="hidden"
                      />

                      {!primaryPreview ? (
                        <>
                          <span className="text-indigo-500 text-3xl">⬆️</span>
                          <p className="text-sm text-gray-600 mt-2">
                            Click to upload primary image
                          </p>
                        </>
                      ) : (
                        <div className="relative">
                          <img
                            src={primaryPreview}
                            className="w-48 h-48 object-cover rounded-lg border shadow-md"
                            alt="Primary preview"
                          />
                          <span className="absolute top-2 right-2 bg-indigo-600 text-white text-xs px-2 py-1 rounded-full">
                            Primary
                          </span>
                        </div>
                      )}
                    </label>
                  </div>

                  {/* Gallery Images */}
                  <div>
                    <label className="block font-medium text-gray-700 mb-3">
                      Gallery Images{" "}
                      <span className="text-xs text-gray-400">(Max 5)</span>
                    </label>

                    <label className="flex flex-col items-center justify-center border-2 border-dashed rounded-xl p-6 cursor-pointer hover:bg-indigo-50 transition">
                      <input
                        type="file"
                        multiple
                        accept="image/*"
                        onChange={handleGalleryImages}
                        className="hidden"
                      />

                      <span className="text-indigo-500 text-3xl">🖼️</span>
                      <p className="text-sm text-gray-600 mt-2">
                        Click to upload gallery images
                      </p>
                    </label>

                    {galleryPreviews.length > 0 && (
                      <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 gap-4 mt-5">
                        {galleryPreviews.map((src, i) => (
                          <div
                            key={i}
                            className="relative group rounded-lg overflow-hidden border shadow-sm"
                          >
                            <img
                              src={src}
                              className="w-full h-32 object-cover transition-transform duration-300 group-hover:scale-105"
                              alt={`Gallery preview ${i + 1}`}
                            />

                            <button
                              type="button"
                              onClick={() => removeGalleryImage(i)}
                              className="absolute top-1 right-1 bg-red-500 text-white text-xs rounded-full w-6 h-6 flex items-center justify-center opacity-0 group-hover:opacity-100 transition"
                            >
                              ✕
                            </button>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                </>
              ) : (
                <div className="text-center py-8 bg-indigo-50 rounded-lg border-2 border-indigo-200">
                  <span className="text-4xl">🎨</span>
                  <p className="text-gray-600 mt-3 font-medium">
                    Upload images for each variant in the Variant section
                  </p>
                  <p className="text-sm text-gray-500 mt-1">
                    Each color variant can have its own set of images
                  </p>
                </div>
              )}
            </div>

            <div className="text-right">
              <button
                type="submit"
                className="bg-indigo-600 hover:bg-indigo-700 text-white font-semibold px-10 py-3 rounded-xl shadow-md transition duration-300"
              >
                Add Product
              </button>
            </div>
          </div>
        </form>
      </motion.div>
    </div>
  );
};

/* ===== Reusable Components ===== */
const Input = ({
  label,
  name,
  type = "text",
  value,
  onChange,
  placeholder,
  required = false,
}) => (
  <div>
    <label className="block font-medium text-gray-700">{label}</label>
    <input
      type={type}
      name={name}
      value={value}
      onChange={onChange}
      placeholder={placeholder}
      required={required}
      className="mt-2 w-full border border-gray-300 rounded-lg px-4 py-2 focus:ring-2 focus:ring-indigo-400"
    />
  </div>
);

const Textarea = ({ label, name, value, onChange, placeholder }) => (
  <div>
    <label className="block font-medium text-gray-700">{label}</label>
    <textarea
      name={name}
      value={value}
      onChange={onChange}
      rows={3}
      placeholder={placeholder}
      className="mt-2 w-full border border-gray-300 rounded-lg px-4 py-2 focus:ring-2 focus:ring-indigo-400"
    />
  </div>
);

const Select = ({ label, name, value, onChange, options }) => (
  <div>
    <label className="block font-medium text-gray-700">{label}</label>
    <select
      name={name}
      value={value}
      onChange={onChange}
      className="mt-2 w-full border border-gray-300 rounded-lg px-4 py-2 focus:ring-2 focus:ring-indigo-400"
    >
      {options.map((opt) => (
        <option key={opt.value} value={opt.value}>
          {opt.label}
        </option>
      ))}
    </select>
  </div>
);

export default ProductAdd;
