import React, { useState, useEffect } from "react";
// import Link from "next/link";
import Cookies from "js-cookie";
import apiInterceptor from "@/interceptor/interceptor";
// import { categoryInterface } from "@/INTERFACES/category";
// import { subCategoryInterface } from "@/INTERFACES/subCategory";
// import { attributeInterface } from "@/INTERFACES/attributeInterface";
import toast, { Toaster } from "react-hot-toast";
import { FaFilter } from "react-icons/fa";
import { useRouter } from "next/router";
import { productInterface } from "@/INTERFACES/product";
import { categoryInterface } from "@/INTERFACES/category";
import { subCategoryInterface } from "@/INTERFACES/subCategory";
import Image from "next/image";
import { Tag, message , Image as AntImage } from "antd";
import { motion } from "framer-motion";


// interface ProductData {
//     categoryId: string;
//     subCategoryId: string;
//     brandId: string;
//     productTitle: string;
//     productFeaturedImage: string;
//     productDescription: string;
//     productShortDescription: string;
//     productType: string;
//     productOriginalPrice: string;
//     productDiscountPrice: string;
//     productDiscountPercentage: string;
//     productSellingPrice: string;
//     productAge: string;
//     productGallery: string[];
//   }

const ShuffleProduct = () => {

    // const [imageUrl, setImageUrl] = useState<string>("");

    const router = useRouter();

    const [categories, setCategories] = useState<any[]>([]);
  
    const [subCategories, setSubCategories] = useState<any[]>([]);
  
    // const [brands, setBrands] = useState<any[]>([]);

    const [products, setProducts] = useState<any[]>([]);
  
    // const handleStateChange = (state: string) => {
    //   setImageUrl(state);
    //   console.log(state);
    // };
  
    // const [uploadedImageLinks, setUploadedImageLinks] = useState<{
    //   [key: number]: string;
    // }>({});
  
    // const handleImageUpload = (id: number, imageUrl: string) => {
    //   setUploadedImageLinks((prevLinks) => ({
    //     ...prevLinks,
    //     [id]: imageUrl,
    //   }));
    // };
  
    const [formData, setFormData] = useState<any>({
      categoryId: "",
      subCategoryId: "",
      productOrder:null,
      productId:""
      // brandId: "",
      // productTitle: "",
      // productFeaturedImage: "",
      // productDescription: "",
      // productShortDescription: "",
      // productType: "",
      // productOriginalPrice: "",
      // productDiscountPrice: "",
      // productDiscountPercentage: "",
      // productSellingPrice: "",
      // productAge: "",
      // productGallery: [],
    });
  
    // const successNotify = () => toast.success("Added Successfully !");
    // const errorNotify = () => toast.error("Something went wrong !");

    const [product, setProduct] = useState<productInterface[]>([]);
    const [currentPage, setCurrentPage] = useState(1);
    const [totalPage, setTotalPage] = useState(1);
    const [isLoading, setIsLoading] = useState(true);
    const [categoriesTable, setCategoriesTable] = useState<{
      [key: string]: categoryInterface;
    }>({});
    const [subCategoriesTable, setSubCategoriesTable] = useState<{
      [key: string]: subCategoryInterface;
    }>({});
    const [isOpen, setIsOpen] = useState(false);
    const [selectedFilter, setSelectedFilter] = useState('Select Filter');
  
    const toggleDropdown = () => setIsOpen(!isOpen);
  
    const handleFilterSelect = async(filter:any) => {
      setSelectedFilter(filter.categoryName);
      setIsOpen(false);
      setIsLoading(true)
      console.log(filter)
      const accessToken = Cookies.get("jazz_token");
  
      // Fetch product data
      const productResponse = await apiInterceptor.get(
        `/api/admin/products?page=${currentPage}`,
        {
          headers: {
            authorization: `Bearer ${accessToken}`,
          },
        }
      );

      // setProduct(productResponse.data.products.data);
      const _applyFilter = productResponse.data.products.data.filter((item:any)=>{
        return item.categoryId === filter._id 
      })
      console.log(_applyFilter)
      setProduct(_applyFilter)
      setIsLoading(false)
    };
  
    const handleChange = async (
      event: React.ChangeEvent<
        HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement
      >
    ) => {
      const { id, value } = event.target;
      console.log(id,value)
      setFormData((prevFormData:any) => ({
        ...prevFormData,
        [id]: value,
      }));
  
      if (id === "categoryId") {
        const subcategoriesResponse = await apiInterceptor.get(
          `/api/getSubCategories/${value}`
        );
        setFormData((prevFormData:any) => ({
        ...prevFormData,
        [id]: value,
      }));
        setSubCategories(subcategoriesResponse.data.subCategories);
      }

      if(id === "subCategoryId"){
        setFormData((prevFormData:any) => ({
          ...prevFormData,
          [id]: value,
        }));
        const productsResponse = await apiInterceptor.get(
          `/api/getProducts?categoryId=${formData.categoryId}&subCategoryId=${value}`
        );
        console.log(productsResponse.data.products.data)
        setProducts(productsResponse.data.products.data)
      }
    };
  
    useEffect(() => {
      const getAllDropdowns = async () => {
        const categoryResponse = await apiInterceptor.get(`/api/getCategories`);
  
        setCategories(categoryResponse.data.categories);
  
        // const brandResponse = await apiInterceptor.get(`/api/getBrands`);
        // setBrands(brandResponse.data.brands);
      };
      getAllDropdowns();
    }, []);

    const handleSubmit = () =>{
      // event.preventDefault();
      if(!formData.categoryId) return toast.error('please select category .')
      if(!formData.subCategoryId) return toast.error('please select sub category')
      if(!formData.productId) return toast.error('Product Id required .')
      if(!formData.productOrder) return toast.error('order no. required .')
      const authToken = Cookies.get("jazz_token");
      const config = {
        headers: {
          authorization: `Bearer ${authToken}`,
        },
      };

      const newOrderdata = {
        id:formData.productId,
        order:Number(formData.productOrder)
      }

      apiInterceptor
          .post("/api/admin/setOrder", newOrderdata, config)
          .then((response) => {
            // console.log(response);
            if(response.status === 200){
              message.success(response.data.message);
              setFormData({
                categoryId: "",
                subCategoryId: "",
                productOrder:"",
                productId:""
              })
              router.reload()
            }
          })
          .catch((err) => {
            console.log(err);
            toast.error("Something went wrong !");
          });

    }
  
    // const handleSubmit = async (event: React.FormEvent) => {
    //   event.preventDefault();
    //   try {
    //     const accessToken = Cookies.get("jazz_token");
    //     const formDataWithImages = {
    //       ...formData,
    //       productFeaturedImage: imageUrl,
    //       productGallery: Object.values(uploadedImageLinks),
    //     };
    //     const response = await apiInterceptor.post(
    //       `/api/admin/products`,
    //       formDataWithImages,
    //       {
    //         headers: {
    //           authorization: `Bearer ${accessToken}`,
    //         },
    //       }
    //     );
    //     if (response) {
    //       successNotify();
    //     }
    //   } catch (error) {
    //     errorNotify();
    //   }
    // };

    useEffect(() => {
      const fetchData = async () => {
        try {
          setIsLoading(true);
          const accessToken = Cookies.get("jazz_token");
  
          // Fetch product data
          const productResponse = await apiInterceptor.get(
            `/api/admin/products?page=${currentPage}`,
            {
              headers: {
                authorization: `Bearer ${accessToken}`,
              },
            }
          );
  
          setProduct(productResponse.data.products.data);

          setTotalPage(productResponse.data.products.pagination.total_pages);
  
          // Fetch category data
          const categoryResponse = await apiInterceptor.get(
            `/api/admin/category?per_page=100`,
            {
              headers: {
                authorization: `Bearer ${accessToken}`,
              },
            }
          );
          const categoryData: categoryInterface[] =
            categoryResponse.data.categories.data;
          // console.log("categoryData",categoryData)
          const categoriesMap: { [key: string]: categoryInterface } = {};
          categoryData.forEach((category) => {
            categoriesMap[category._id] = category;
            // console.log("CATEGORY",category)
          });
  
          // Set categories in the state
          setCategoriesTable(categoriesMap);
  
          //fetch subcategory data
          const subCategoryResponse = await apiInterceptor.get(
            `/api/admin/subCategory?per_page=1000`,
            {
              headers: {
                authorization: `Bearer ${accessToken}`,
              },
            }
          );
  
          const subCategoryData: subCategoryInterface[] =
            subCategoryResponse.data.subCategories.data;
  
          const subCategoriesMap: { [Key: string]: subCategoryInterface } = {};
          subCategoryData.forEach((subCategory) => {
            subCategoriesMap[subCategory._id] = subCategory;
          });
          setSubCategoriesTable(subCategoriesMap);
        } catch (error) {
          console.error("Error:", error);
        } finally {
          setIsLoading(false);
        }
      };
      fetchData();
    }, [currentPage]);
  
    const handleNextPage = () => {
      if (currentPage < totalPage) {
        setCurrentPage(currentPage + 1);
      }
    };
  
    const handlePrevPage = () => {
      if (currentPage > 1) {
        setCurrentPage(currentPage - 1);
      }
    };

  return (
    <div className="flex flex-col">
      <Toaster/>
      <div className="space-y-8 w-[100%] md:w-[50%] md:m-auto p-8 shadow-xl">
        <p className="font-bold text-xl text-[#FF332B] m-3">Set New Order </p>
        <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 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 "
                  onChange={handleChange}
                >
                  <option disabled selected>
                    Select Category
                  </option>
                  {categories.map((item) => {
                    return (
                      <option value={item._id} key={item._id}>
                        {item.categoryName}
                      </option>
                    );
                  })}
                </select>
              </div>

          <div>
            <label
              htmlFor="subCategoryId"
              className="block mb-2 text-sm font-medium text-[#FF332B] "
            >
              Sub Category
            </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 "
              onChange={handleChange}
              >
             <option disabled selected>
                    Select Sub Category
                  </option>
                  {subCategories.length >= 1 ? (
                    subCategories.map((item) => {
                      return (
                        <option value={item._id} key={item._id}>
                          {item.subCategoryName}
                        </option>
                      );
                    })
                  ) : (
                    <option disabled>No Record Found !</option>
                  )}
            </select>
          </div>

          <div>
            <label
              htmlFor="ProductId"
              className="block mb-2 text-sm font-medium text-[#FF332B] "
            >
              Product Name
            </label>
            <select
              id="productId"
              required
              onChange={handleChange}
              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 "
            >
              <option selected disabled value="">
                Select Product
              </option>
              {products.length >= 1 ? (
                    products.map((item) => {
                      return (
                        <option value={item._id} key={item._id}>
                          {item.productTitle}
                        </option>
                      );
                    })
                  ) : (
                    <option disabled>No Record Found !</option>
                  )}
            </select>
          </div>

          <div className="mr-1 my-2">
            <label
              htmlFor=""
              className="block mb-2 text-sm font-medium text-[#FF332B] "
            >
              Order
            </label>
            <input
              type="text"
              id="productOrder"
              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 "
              required
              onChange={handleChange}
            />
          </div>
        </div>
        <button onClick={()=>handleSubmit()} className="bg-[#FF332B] text-white rounded-lg p-3 my-[1rem] mb-[2rem] w-[150px] ml-4 md:m-auto">Submit</button>
      </div>

      {/* <div className="ml-2 text-center md:ml-[20px] md:text-left">
      <button onClick={()=>handleSubmit()} className="bg-[#FF332B] text-white rounded-lg p-3 my-[1rem] mb-[2rem] w-[150px] ml-4">Submit</button>
      </div> */}

      {/* <div className="overflow-x-auto sm:-mx-6 lg:-mx-8">
        <div className="inline-block min-w-full py-2 sm:px-6 lg:px-8">
          <div className="overflow-hidden">
            <table className="min-w-full text-left text-sm font-light">
              <thead className="border-b bg-white font-medium">
                <tr>
                  <th className="px-6 py-4">#</th>
                  <th className="px-6 py-4">products</th>
                  <th className=" py-4 text-right px-[2rem]">Action</th>
                </tr>
              </thead>
            </table>
          </div>
        </div>
      </div> */}

<div className="flex justify-end">
    <div className="relative">
      <button
        className="px-4 py-2"
        onClick={toggleDropdown}
      >
        <FaFilter className="inline text-gray-500 text-xl m-2" size={20}/>
        
        <Tag>{selectedFilter}</Tag>
      </button>
      {isOpen && (
        <motion.div 
          animate={{y:10,x:-90}}
          className="absolute mt-2 w-48 bg-black shadow-lg rounded-md z-10">
          <ul className="py-1">
            {categories.map((filter, index) => (
              <motion.li
              whileHover={{scale:0.9}}
                key={index}
                className={`px-4 py-2 hover:bg-red-500 cursor-pointer text-white ${selectedFilter === filter.categoryName ? "bg-red-500": ""}`}
                onClick={() => handleFilterSelect(filter)}
              >
                {filter.categoryName}
              </motion.li>
            ))}
          </ul>
        </motion.div>
      )}
    </div>
</div>

{isLoading ? (
          <div className="flex justify-center items-center">
            <Image
              src={"/images/loading.gif"}
              height={50}
              width={50}
              alt="loading..."
            />
          </div>
        ) : (
          <>
            <div className="">
              <div className="">
                <div className="">
                  <table className="min-w-full text-left text-sm font-light overflow-x-auto">
                    <thead className="border-b bg-white font-medium">
                      <tr>
                        <th className="px-6 py-4">#</th>
                        <th className="px-6 py-4">IMAGE</th>
                        <th className="py-4 px-6">PRODUCT NAME</th>
                        <th className="px-6 py-4">CATEGORY</th>
                        <th className="px-6 py-4">SUBCATEGORY</th>
                        <th className="px-6 py-4">SELLER NAME</th>
                        <th className="px-6 py-4">ORDER NO.</th>
                        {/* <th className="px-6 py-4">SELLING PRICE</th>
                        <th className="px-6 py-4">UPLOAD DATE</th> */}
                        {/* <th className=" py-4 text-right px-[2rem]">Action</th> */}
                      </tr>
                    </thead>

                    {product.map((item, index) => (
                      <tbody key={item._id}>
                        <tr className="border-b bg-neutral-10 dark:border-neutral-500 hover:bg-gray-200">
                          <td className="px-6 py-1 font-medium">{index + 1}</td>
                          <td className="px-6 py-1">
                            <AntImage
                              src={`https://api.jazzagain.com/public/${item.productFeaturedImage}`}
                              height={60}
                              width={60}
                              alt=""
                            />
                          </td>

                          <td className="px-6 py-1">{item.productTitle}</td>
                          <td className="px-6 py-1">
                            {categoriesTable[item.categoryId]
                              ? categoriesTable[item.categoryId].categoryName
                              : "-"}
                          </td>
                          <td className="px-6 py-1">
                            {subCategoriesTable[item.subCategoryId]
                              ? subCategoriesTable[item.subCategoryId]
                                  .subCategoryName
                              : "-"}
                          </td>
                          <td className=" px-6 py-1">
                            {item.seller.firstName}
                          </td>
                          <td className="px-6 py-1">
                            {item.order ? item.order : 'Not set'}
                          </td>
                          {/* <td className="px-6 py-4">
                            {item.productSellingPrice}
                          </td> */}
                          {/* <td className="px-4 py-4">{item.created_at.split('T')[0]}</td> */}
                          

                          {/* <td className="px-6 py-4 flex flex-row-reverse justify-center items-center">
                            <button
                              className="bg-[#FE342B]  hover:bg-[#d13931] rounded text-white mx-2 px-3 py-2"
                              onClick={() => handleDelete(item._id)}
                            >
                              Delete
                            </button>
                            <Link
                              href={`/admin/product/update-product/${item._id}`}
                              className="bg-[#383736] transition-all duration-300 hover:bg-[#2d2d2c] rounded text-white px-3 mx-2 py-2"
                            >
                              Update
                            </Link>
                          </td> */}
                        </tr>
                      </tbody>
                    ))}
                  </table>
                </div>
              </div>
            </div>
            <div className="mx-3 mt-4 flex justify-between sm:px-[2rem]">
              <button
                onClick={handlePrevPage}
                className="bg-[#383736] hover:bg-[#FE342B] text-white px-4 py-2 rounded"
              >
                Previous
              </button>
              <button
                onClick={handleNextPage}
                className="bg-[#383736] hover:bg-[#FE342B] text-white px-4 py-2 rounded"
              >
                Next
              </button>
            </div>
          </>
        )}

    </div>
  );
};

export default ShuffleProduct;
