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[]>([]);
  const [attribute, setAttribute] = useState<any[]>([]);

  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 = async (event: React.ChangeEvent<any>) => {
    const { id, value } = event.target;
    setFormData((prev) => ({
      ...prev,
      [id]: value,
    }));
  };

  useEffect(() => {
    const getAllCategoryDropdowns = async () => {
      const accessToken = Cookies.get("jazz_token");
      const categoryResponse = await apiInterceptor.get(
        `/api/admin/category?per_page=250`,
        {
          headers: {
            authorization: `Bearer ${accessToken}`,
          },
        }
      );
      setCategories(categoryResponse.data.categories.data);
    };
    getAllCategoryDropdowns();
  }, []);

  useEffect(() => {
    const getAllSubCategoryDropdowns = async () => {
      const accessToken = Cookies.get("jazz_token");
      const subCategoryResponse = await apiInterceptor.get(
        `/api/admin/subCategory?per_page=500`,
        {
          headers: {
            authorization: `Bearer ${accessToken}`,
          },
        }
      );
      setSubCategories(subCategoryResponse.data.subCategories.data);
    };
    getAllSubCategoryDropdowns();
  }, []);

  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}`,
          },
        }
      );
      console.log("attribute data", response.data.attributes);
      setAttributes(response.data.attributes);
    } catch (error) {
      console.error("Error:", error);
    }
  };

  useEffect(() => {
    if (selectedCategoryId && selectedSubCategoryId) {
      getAttributes();
    } else {
      setAttributes([]);
    }
  }, [selectedCategoryId, selectedSubCategoryId]);

  useEffect(() => {
    const getAllAttributeDropdowns = async () => {
      const accessToken = Cookies.get("jazz_token");
      const attributeResponse = await apiInterceptor.get(
        `/api/admin/attributes?per_page=2000`,
        {
          headers: {
            authorization: `Bearer ${accessToken}`,
          },
        }
      );
      setAttribute(attributeResponse.data.attributes.data);
      console.log("attribute List", attributeResponse.data.attributes.data);
    };
    getAllAttributeDropdowns();
  }, []);

  const handleSubmit = async (event: React.FormEvent) => {
    event.preventDefault();
    console.log("FORM DATA", formData);
    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 mx-4 text-3xl sm:text-4xl tracking-tight font-extrabold text-center text-[#FE342B]">
          Add Variation Name
        </h2>
        <Toaster
          toastOptions={{
            className: "",
            duration: 5000,
            style: {
              marginTop: "4rem",
              background: "#FE342B",
              color: "#fff",
            },
          }}
        />

        <form action="#" onSubmit={handleSubmit} className="space-y-8">
          <div className="space-y-8">
            <div>
              <label
                htmlFor="categoryId"
                className="block mb-2 text-sm font-medium text-[#FF332B] "
              >
                Category
              </label>
              <select
                id="categoryId"
                required
                className="shadow-sm focus:outline-none bg-gray-50 border border-gray-300 text-[#FF332B] text-sm rounded-lg focus:ring-primary-500 focus:border-primary-500 block w-full p-2.5 "
                value={selectedCategoryId}
                onChange={(e) => setSelectedCategoryId(e.target.value)}
              >
                <option selected disabled value="">
                  Select Category
                </option>
                {categories.map((item) => (
                  <option value={item._id} key={item._id}>
                    {item.categoryName}
                  </option>
                ))}
              </select>
            </div>

            <div className="mb-4">
              <label
                htmlFor="subCategoryId"
                className="block mb-2 text-sm font-medium text-[#FF332B] "
              >
                Subcategory
              </label>
              <select
                id="subCategoryId"
                required
                className="shadow-sm focus:outline-none bg-gray-50 border border-gray-300 text-[#FF332B] text-sm rounded-lg focus:ring-primary-500 focus:border-primary-500 block w-full p-2.5 "
                value={selectedSubCategoryId}
                onChange={(e) => setSelectedSubCategoryId(e.target.value)}
              >
                <option disabled value="">
                  Select Subcategory
                </option>
                {subCategories
                  .filter((item) => item.categoryId === selectedCategoryId)
                  .map((item) => (
                    <option value={item._id} key={item._id}>
                      {item.subCategoryName}
                    </option>
                  ))}
              </select>
            </div>

            <div className="mb-4">
              <label
                htmlFor="attributeId"
                className="block mb-2 text-sm font-medium text-[#FF332B] "
              >
                Attribute
              </label>
              <select
                id="attributeId"
                name="attributeId"
                required
                onChange={handleChange}
                value={formData.attributeId}
                className="shadow-sm focus:outline-none bg-gray-50 border border-gray-300 text-[#FF332B] text-sm rounded-lg focus:ring-primary-500 focus:border-primary-500 block w-full p-2.5 "
                // value={selectedAttributeId}
                // onChange={(e) => setSelectedAttributeId(e.target.value)}
              >
                <option disabled value="">
                  Select Attribute
                </option>
                {attributes
                  .filter(
                    (item) => item.subCategoryId === selectedSubCategoryId
                  )
                  .map((item) => (
                    <option value={item._id} key={item._id}>
                      {item.attributeName}
                    </option>
                  ))}
              </select>
            </div>

            <div className="mb-4">
              <label
                htmlFor="variationName"
                className="block mb-2 text-sm font-medium text-[#FF332B] "
              >
                Variation Name
              </label>
              <input
                type="text"
                id="variationName"
                name="variationName"
                value={formData.variationName}
                required
                onChange={handleChange}
                className="shadow-sm bg-gray-50 border border-gray-300 text-[#FF332B] text-sm rounded-lg focus:ring-primary-500 focus:border-primary-500 block w-full p-2.5 "
              />
            </div>

            <button
              type="submit"
              className="py-3 px-5 text-sm font-medium text-center rounded-lg bg-gray-300 sm:w-fit hover:bg-[#FF332B] hover:text-white transition-all duration-300"
            >
              Submit
            </button>
          </div>
        </form>
      </div>
    </section>
  );
};

export default AddVariation;
