"use client";
import React, { useEffect, useState } from "react";
import toast, { Toaster } from "react-hot-toast";
import Cookies from "js-cookie";
import { categoryInterface } from "@/INTERFACES/category";
import { subCategoryInterface } from "@/INTERFACES/subCategory";
import { attributeInterface } from "@/INTERFACES/attributeInterface";
import apiInterceptor from "@/interceptor/interceptor";

interface VariationData {
  variationName: string;
  variationValue: string | null;
  shortDescription: string | null;
  longDescription: string | null;
  attributeId: string;
}

const AddVariation = () => {
  const [categories, setCategories] = useState<categoryInterface[]>([]);
  const [subCategories, setSubCategories] = useState<subCategoryInterface[]>([]);
  const [attributes, setAttributes] = useState<attributeInterface[]>([]);

  // Selection states for filtering
  const [selectedCategoryId, setSelectedCategoryId] = useState<string>("");
  const [selectedSubCategoryId, setSelectedSubCategoryId] = useState<string>("");

  const [formData, setFormData] = useState<VariationData>({
    variationName: "",
    variationValue: "",
    shortDescription: "",
    longDescription: "",
    attributeId: "",
  });

  const successNotify = () => toast.success("Added Successfully !");
  const errorNotify = () => toast.error("Something went wrong !");

  const handleChange = (event: React.ChangeEvent<any>) => {
    const { id, value } = event.target;
    setFormData((prev) => ({
      ...prev,
      [id]: value,
    }));
  };

  // 1. Fetch All Categories
  useEffect(() => {
    const getAllCategoryDropdowns = async () => {
      try {
        const accessToken = Cookies.get("jazz_token");
        const res = await apiInterceptor.get(`/api/admin/category?per_page=250`, {
          headers: { authorization: `Bearer ${accessToken}` },
        });
        setCategories(res.data.categories.data || []);
      } catch (error) {
        console.error("Error fetching categories", error);
      }
    };
    getAllCategoryDropdowns();
  }, []);

  // 2. Fetch All Subcategories (once on mount)
  useEffect(() => {
    const getAllSubCategoryDropdowns = async () => {
      try {
        const accessToken = Cookies.get("jazz_token");
        const res = await apiInterceptor.get(`/api/admin/subCategory?per_page=500`, {
          headers: { authorization: `Bearer ${accessToken}` },
        });
        setSubCategories(res.data.subCategories.data || []);
      } catch (error) {
        console.error("Error fetching subcategories", error);
      }
    };
    getAllSubCategoryDropdowns();
  }, []);

  // 3. Fetch Attributes based on selected IDs
  const getAttributes = async () => {
    try {
      const accessToken = Cookies.get("jazz_token");
      const response = await apiInterceptor.get(
        `/api/getAttributes?categoryId=${selectedCategoryId}&subCategoryId=${selectedSubCategoryId}`,
        {
          headers: { authorization: `Bearer ${accessToken}` },
        }
      );
      setAttributes(response.data.attributes || []);
    } catch (error) {
      console.error("Error fetching attributes:", error);
    }
  };

  useEffect(() => {
    if (selectedCategoryId && selectedSubCategoryId) {
      getAttributes();
    } else {
      setAttributes([]);
    }
  }, [selectedCategoryId, selectedSubCategoryId]);

  const handleSubmit = async (event: React.FormEvent) => {
    event.preventDefault();
    try {
      const accessToken = Cookies.get("jazz_token");
      const response = await apiInterceptor.post(`/api/admin/variations`, formData, {
        headers: { authorization: `Bearer ${accessToken}` },
      });
      if (response.status === 201) {
        successNotify();
        setFormData({
          variationName: "",
          variationValue: "",
          shortDescription: "",
          longDescription: "",
          attributeId: "",
        });
      }
    } catch (error) {
      errorNotify();
    }
  };

  return (
    <section className="bg-white w-[80%] lg:w-[50%] mx-auto h-screen">
      <div className="py-8 lg:py-16 px-4 mx-auto max-w-screen-sm">
        <h2 className="mb-4 text-3xl font-extrabold text-center text-[#FE342B]">
          Add Variation Name
        </h2>
        <Toaster toastOptions={{ style: { background: "#FE342B", color: "#fff" } }} />

        <form onSubmit={handleSubmit} className="space-y-6">
          {/* 1. Category */}
    {/* 1. Category Dropdown */}
<div>
  <label className="block mb-2 text-sm font-medium text-[#FF332B]">Category</label>
  <select
    required
    className="shadow-sm bg-gray-50 border border-gray-300 text-[#FF332B] text-sm rounded-lg block w-full p-2.5 focus:outline-none"
    value={selectedCategoryId}
    onChange={(e) => {
      const newId = e.target.value;
      setSelectedCategoryId(newId);
      setSelectedSubCategoryId(""); // Reset sub-category
      setAttributes([]);            // Clear attributes
      setFormData((prev) => ({ ...prev, attributeId: "" })); 
    }}
  >
    <option value="" disabled>Select Category</option>
    {categories.map((item: any) => (
      // Yahan (item as any) use karne se TS error khatam ho jayega
      <option value={item.id || item.id} key={item.id || item.id}>
        {item.categoryName}
      </option>
    ))}
  </select>
</div>

{/* 2. Subcategory Dropdown - Fixed Logic */}
<div className="mt-4">
  <label className="block mb-2 text-sm font-medium text-[#FF332B]">Subcategory</label>
  <select
    required
    className="shadow-sm bg-gray-50 border border-gray-300 text-[#FF332B] text-sm rounded-lg block w-full p-2.5 focus:outline-none"
    value={selectedSubCategoryId}
    onChange={(e) => {
      setSelectedSubCategoryId(e.target.value);
      setFormData((prev) => ({ ...prev, attributeId: "" }));
    }}
  >
    <option value="" disabled>Select Subcategory</option>
    {subCategories
      .filter((sub: any) => {
        // Strict mapping logic
        const catIdInSub = sub.categoryId || sub.category_id; 
        return String(catIdInSub) === String(selectedCategoryId);
      })
      .map((item: any) => (
        <option value={item.id || item.id} key={item.id || item.id}>
          {item.subCategoryName}
        </option>
      ))}
  </select>
</div>

          {/* 3. Attribute (Loaded from API based on selections) */}
          <div>
            <label className="block mb-2 text-sm font-medium text-[#FF332B]">Attribute</label>
            <select
              id="attributeId"
              required
              className="shadow-sm bg-gray-50 border border-gray-300 text-[#FF332B] text-sm rounded-lg block w-full p-2.5 focus:outline-none"
              value={formData.attributeId}
              onChange={handleChange}
            >
              <option value="" disabled>Select Attribute</option>
              {attributes.map((item) => (
                <option value={item.id} key={item.id}>{item.attributeName}</option>
              ))}
            </select>
          </div>

          {/* 4. Variation Name */}
          <div>
            <label className="block mb-2 text-sm font-medium text-[#FF332B]">Variation Name</label>
            <input
              type="text"
              id="variationName"
              required
              className="shadow-sm bg-gray-50 border border-gray-300 text-[#FF332B] text-sm rounded-lg block w-full p-2.5 focus:outline-none"
              value={formData.variationName}
              onChange={handleChange}
            />
          </div>

          <button
            type="submit"
            className="py-3 px-5 text-sm font-medium text-center rounded-lg bg-gray-300 hover:bg-[#FF332B] hover:text-white transition-all duration-300"
          >
            Submit
          </button>
        </form>
      </div>
    </section>
  );
};

export default AddVariation;