import React, { useState, useEffect } from "react";
import Link from "next/link";
import Cookies from "js-cookie";
import Image from "next/image";
import apiInterceptor from "@/interceptor/interceptor";
import { productInterface } from "@/INTERFACES/product";
import { categoryInterface } from "@/INTERFACES/category";
import { subCategoryInterface } from "@/INTERFACES/subCategory";

const Index = () => {
  const [product, setProduct] = useState<productInterface[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPage, setTotalPage] = useState(1);
  const [isLoading, setIsLoading] = useState(true);
  const [categories, setCategories] = useState<{
    [key: string]: categoryInterface;
  }>({});
  const [subCategories, setSubCategories] = useState<{
    [key: string]: subCategoryInterface;
  }>({});

  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
        setCategories(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;
        });
        setSubCategories(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);
    }
  };

  const handleDelete = async (productId: string) => {
    const accessToken = Cookies.get("jazz_token");
    await apiInterceptor.delete(`/api/admin/products/${productId}`, {
      headers: { authorization: `Bearer ${accessToken}` },
    });
    setProduct((prevData) => prevData.filter((item) => item._id !== productId));
  };

  return (
    <>
      <div className="flex flex-col">
      
        {isLoading ? (
          <div className="flex justify-center items-center">
            <Image
              src={"/images/loading.gif"}
              height={50}
              width={50}
              alt="loading..."
            />
          </div>
        ) : (
          <>
            <div className="">
              <div className="inline-block">
                <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">SELLER NAME</th>
                        {/* <th className="px-6 py-4">BUYER NAME</th> */}
                        <th className=" py-4 px-6">STATUS</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">
                            <Image
                              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">
                            {item.seller.firstName}
                          </td>
                          {/* <td className=" px-6 py-4">
                            Buyer Name
                          </td> */}
                          <td className=" px-6 py-1">
                            {item.productAvailability == '1' ? 'unsold' : 'unsold'}
                          </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 Index;