import React, { useState, ChangeEvent, FormEvent, useEffect } from "react";
import Cookies from "js-cookie";
import toast, { Toaster } from "react-hot-toast";
import SingleImageBox from "@/components/SingleImageBox";
import apiInterceptor from "@/interceptor/interceptor";

// Interface for the product data
interface subCategoryData {
  categoryId: string;
  subCategoryName: string;
  shortDescription: string;
  longDescription: string;
  productFeaturedImage: string;
  type:string
}

const SubCategory = () => {
  const [imageUrl, setImageUrl] = useState<string>("");

  const [categories, setCategories] = useState<any[]>([]);

  const handleStateChange = (state: string) => {
    setImageUrl(state);
    console.log(state);
  };

  const [formData, setFormData] = useState<subCategoryData>({
    categoryId: "",
    subCategoryName: "",
    shortDescription: "",
    longDescription: "",
    productFeaturedImage: "",
    type:""
  });

  const successNotify = () => toast.success("Added Successfully !");
  const errorNotify = () => toast.error("Something went wrong !");

  // Handle input and textarea changes
  const handleChange = async (
    event: React.ChangeEvent<
      HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement
    >
  ) => {
    const { id, value } = event.target;
    setFormData((prevFormData) => ({
      ...prevFormData,
      productFeaturedImage: imageUrl,
      [id]: value,
    }));
   }

   
  useEffect(() => {
    const getAllCategories = async () => {
      const accessToken = Cookies.get("jazz_token");
      const categoryResponse = await apiInterceptor.get(
        `/api/admin/category?per_page=50`,
        {
          headers: {
            authorization: `Bearer ${accessToken}`,
          },
        }
      );
      console.log("categorydata",categoryResponse.data.categories.data)
      setCategories(categoryResponse.data.categories.data)
    };
    getAllCategories();
  }, []);

  const handleSubmit = async (event: React.FormEvent) => {
    event.preventDefault();
    // return console.log(formData);
    try {
      console.log(formData);
      const accessToken = Cookies.get("jazz_token");

      const response = await apiInterceptor.post(
        `/api/admin/subCategory`,
        formData,
        {
          headers: {
            authorization: `Bearer ${accessToken}`,
          },
        }
      );
      console.log(response.data)
      // console.log("Response:", response.data);
      if (response) successNotify();
    } catch (error) {
      // console.error("Error:", error);
      errorNotify();
    }
  };
  
  return (
    <section className="bg-white">
      <div className="py-8 lg:py-16 px-4 mx-auto max-w-screen-md">
        <h2 className="mb-4 text-3xl sm:text-4xl tracking-tight font-extrabold text-center text-[#FE342B] ">
          Add Sub Category
        </h2>
        <Toaster
          toastOptions={{
            // Define default options
            className: "",
            duration: 5000,
            style: {
              marginTop: "3rem",
              background: "#FE342B",
              color: "#fff",
            },
          }}
        />

        <form action="#" className="space-y-8" onSubmit={handleSubmit}>
          <div className="grid lg:grid-cols-2">
            <div className="space-y-8">
              <div>
                <label
                  htmlFor="categoryId"
                  className="block mb-2 text-sm font-medium text-[#FE342B] "
                >
                  Category
                </label>
                <select
                  id="categoryId"
                  required
                  className="shadow-sm bg-gray-50 border border-gray-300 text-[#FE342B] text-sm rounded-lg focus:ring-primary-500 focus:border-primary-500 block w-full p-2.5 "
                  onChange={handleChange}
                >
                  <option disabled selected={true}>
                    Select Category
                  </option>
                  {categories.map((item) => {
                    return (
                      <option value={item._id} key={item._id}>
                        {item.categoryName}
                      </option>
                    );
                  })}
                </select>
              </div>

              <div>
                <label
                  htmlFor="subCategoryName"
                  className="block mb-2 text-sm font-medium text-[#FE342B] "
                >
                  Sub Category Name
                </label>
                <input
                  type="text"
                  id="subCategoryName"
                  className="shadow-sm bg-gray-50 border border-gray-300 text-[#FE342B] text-sm rounded-lg focus:ring-primary-500 focus:border-primary-500 block w-full p-2.5 "
                  placeholder="i.e Fashion"
                  value={formData.subCategoryName}
                  onChange={handleChange}
                  required
                />
              </div>

              <div className="text-sm pb-[1rem]">
            <label htmlFor="type" className="block mb-2 text-sm font-medium text-[#FE342B]">Type </label>
            <select
              name="type"
              id="type"
              style={{ display: "flex", width: "100%", maxWidth: "520px" }}
              className="flex my-1 p-2 rounded-lg border border-gray-300 text-[#FE342B]"
              onChange={handleChange}
            >
              
              <option value='' disabled selected={true}>Select Type</option>
              <option value={"simple"}>Standard product</option>
              <option value={"variable"}>
                Product with size/color options
              </option>
            </select>
          </div>

            
            </div>

            <div className="flex items-center justify-center w-full mt-4">
              <SingleImageBox onStateChange={handleStateChange} />
            </div>
          </div>

          <div className="sm:col-span-2">
            <label
              htmlFor="shortDescription"
              className="block mb-2 text-sm font-medium text-[#FE342B] "
            >
              Short Description
            </label>
            <textarea
              id="shortDescription"
              rows={2}
              className="block p-2.5 w-full text-sm text-[#FE342B] bg-gray-50 rounded-lg shadow-sm border border-gray-300 focus:ring-primary-500 focus:border-primary-500 "
              placeholder="Short description here..."
              value={formData.shortDescription}
              onChange={handleChange}
            ></textarea>
          </div>
          <div className="sm:col-span-2">
            <label
              htmlFor="longDescription"
              className="block mb-2 text-sm font-medium text-[#FE342B] "
            >
              Long Description
            </label>
            <textarea
              id="longDescription"
              rows={6}
              className="block p-2.5 w-full text-sm text-[#FE342B] bg-gray-50 rounded-lg shadow-sm border border-gray-300 focus:ring-primary-500 focus:border-primary-500 "
              placeholder="Add description here..."
              value={formData.longDescription}
              onChange={handleChange}
            ></textarea>
          </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-[#FE342B] hover:text-white transition-all duration-300"
          >
            Submit
          </button>
        </form>
      </div>
    </section>
  );
};

export default SubCategory;
