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 subCategoryData {
  categoryId: string;
  productId: string;
  image: string;
  desktopImage: string;
  active?: number;
  deleted?: boolean;
}


const AddBanner = () => {
  const [imageUrl, setImageUrl] = useState<string>("");
const [bannerType, setBannerType] = useState<string>("");

  const [categories, setCategories] = useState<any[]>([]);
  const [products, setProducts] = useState<any>([]);

const handleStateChange = (url: string) => {
  setImageUrl(url);

  if (!bannerType) {
    toast.error("Please select banner type (Web/App) before uploading image.");
    return;
  }

  setFormData((prev) => ({
    ...prev,
    image: bannerType === "app" ? url : prev.image,
    desktopImage: bannerType === "web" ? url : prev.desktopImage,
    ...(bannerType === "web" && { active: 0, deleted: false }), // Add both fields conditionally
  }));

  console.log("Uploaded URL:", url, "Saved to:", bannerType);
};




  const [formData, setFormData] = useState<subCategoryData>({
    categoryId: "",
    productId: "",
    image: "",
      desktopImage: ""

  });

  const successNotify = () => toast.success("Added Successfully !");
  const errorNotify = () => toast.error("Something went wrong !");

 const handleChange = async (
  event: React.ChangeEvent<
    HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement
  >
) => {
  const { id, value } = event.target;

  if (id === "bannerType") {
    setBannerType(value);
    return;
  }

  setFormData((prevFormData) => ({
    categoryId: id === "categoryId" ? value : prevFormData.categoryId,
    productId:
      id === "productId"
        ? value
        : id === "categoryId"
        ? ""
        : prevFormData.productId,
    image: prevFormData.image,
    desktopImage: prevFormData.desktopImage,
  }));

  if (id === "categoryId") {
    const accessToken = Cookies.get("jazz_token");
    const productResponse = await apiInterceptor.get(
      `/api/admin/products?categoryId=${value}`,
      {
        headers: {
          authorization: `Bearer ${accessToken}`,
        },
      }
    );
    setProducts(productResponse.data.products.data);
  }
};


  useEffect(() => {
    const getAllCategories = async () => {
      const accessToken = Cookies.get("jazz_token");
      const categoryResponse = await apiInterceptor.get(`/api/getCategories/`, {
        headers: {
          authorization: `Bearer ${accessToken}`,
        },
      });
      setCategories(categoryResponse.data.categories);
    };
    getAllCategories();
  }, []);

  const handleSubmit = async (event: React.FormEvent) => {
    event.preventDefault();
    try {
      console.log(formData);
      const accessToken = Cookies.get("jazz_token");
      console.log(accessToken);
      const response = await apiInterceptor.post(
        `/api/admin/banner`,
        formData,
        {
          headers: {
            authorization: `Bearer ${accessToken}`,
          },
        }
      );
      console.log(response);
      if (response) successNotify();
    } catch (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 Banner
        </h2>
        <Toaster
          toastOptions={{
            duration: 5000,
          }}
        />

        <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="productId"
                  className="block mb-2 text-sm font-medium text-[#FE342B] "
                >
                  Product
                </label>
                <select
                  id="productId"
                  name="productId"
                  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 selected={true}>
                    Select Product
                  </option>
                  {products.map((item: any) => {
                    return (
                      <option value={item._id} key={item._id}>
                        {item.productTitle}
                      </option>
                    );
                  })}
                </select>
              </div>

<div>
  <label
    htmlFor="bannerType"
    className="block mb-2 text-sm font-medium text-[#FE342B]"
  >
    Type
  </label>
  <select
    id="bannerType"
    name="bannerType"
    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 Type
    </option>
    <option value="web">Web</option>
    <option value="app">App</option>
  </select>
</div>


            </div>

            <div className="flex items-center justify-center w-full mt-4">
              <SingleImageBox onStateChange={handleStateChange}  />
            </div>
          </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 AddBanner;


