import React, { useState } from "react";
import Cookies from "js-cookie";
import Link from "next/link";
import apiInterceptor from "@/interceptor/interceptor";
import Image from "next/image";
import { userActivity } from "@/components/commonFunctions/userActivity";
import { useRouter } from "next/router";
import jwt from "jsonwebtoken";



const ViewSubCategory = () => {

  
  const token: any = Cookies.get("jazz_admin_token");

  const decodedToken = jwt.decode(token);

  const userId = decodedToken ? decodedToken.sub : null;
  const [subCategoryData, setSubCategoryData] = React.useState<any[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [isLoading, setIsLoading] = useState(true);
  // const [categoryId, setCategoryId] = useState('')

  React.useEffect(() => {
    const getSubCategory = async () => {
      try {
        setIsLoading(true);
        const accessToken = Cookies.get("jazz_token");
        console.log(accessToken);
        const response = await apiInterceptor.get(
          `/api/admin/subCategory?page=${currentPage}`,
          {
            headers: {
              authorization: `Bearer ${accessToken}`,
            },
          }
        );

        setSubCategoryData(response.data.subCategories.data);
        setTotalPages(response.data.subCategories.pagination.total_pages);
      } catch (error) {
        console.error("Error:", error);
      } finally {
        setIsLoading(false);
      }
    };
    getSubCategory();
  }, [currentPage]);

  // React.useEffect(() => {
  //   const accessToken = Cookies.get("jazz_token");
  //   const getCategory = async () => {
  //     const categoryResponse = await apiInterceptor.get(
  //       `/api/admin/category`,
  //       {
  //         headers: {
  //           authorization: `Bearer ${accessToken}`,
  //         },
  //       }
  //     );
  //     setCategoryId(categoryResponse.data.categories.data)
  //     console.log("category", categoryResponse.data.categories.data);
  //   };
  //   getCategory();
  // }, []);

  const handleDelete = async (subCategoryId: string) => {
    try {
      const accessToken = Cookies.get("jazz_token");
      await apiInterceptor.delete(`/api/admin/subCategory/${subCategoryId}`, {
        headers: {
          authorization: `Bearer ${accessToken}`,
        },
      });
      // Update the state to remove the deleted subcategory
      setSubCategoryData((prevData) =>
        prevData.filter((item) => item._id !== subCategoryId)
      );
    } catch (error) {
      console.error("Error deleting category:", error);
    }
  };

  const handleNextPage = () => {
    if (currentPage < totalPages) {
      setCurrentPage(currentPage + 1);
    }
  };

  const handlePrevPage = () => {
    if (currentPage > 1) {
      setCurrentPage(currentPage - 1);
    }
  };

  return (
    <div className="flex flex-col p-8">


<Link
           className="ml-[4rem] lg:ml-4 px-3 mx-4 py-2 hover:bg-[#FE342B] bg-[#383736] transition-all duration-300 rounded max-w-fit text-white my-2"
           href={"/admin/subCategory/addSubCategory"}
           onClick={() => {
            if (userId) {
              userActivity(
                userId,
                "admin",
                "Add New SubCategory",
                {
                  pageVisit: `/`,
                },
                navigator.userAgent
              );
            } else {
              console.error("User ID is not available");
            }
          }}
      >
        Add New SubCategory
        </Link>

      {isLoading ? (
        <div className="flex justify-center items-center">
          <Image
            src={"/images/loading.gif"}
            height={50}
            width={50}
            alt="loading..."
          />
        </div>
      ) : (
        <>
          <div className="overflow-x-auto">
            <div className="inline-block min-w-full py-2">
              <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">CATEGORY</th> */}
                      <th className="px-6 py-4">SUB CATEGORY</th>
                      <th className="px-[2rem] py-4 text-right" colSpan={2}>
                        Action
                      </th>
                    </tr>
                  </thead>
                  {subCategoryData.map((item, index) => (
                    <tbody key={item._id}>
                      <tr className="border-b bg-neutral-100 dark:border-neutral-500 hover:bg-gray-200">
                        <td className="whitespace-nowrap px-6 py-4 font-medium">
                          {index + 1}
                        </td>
                        {/* <td className="whitespace-nowrap px-6 py-4">
                          {item.categoryId}
                        </td> */}
                        <td className="whitespace-nowrap px-6 py-4">
                          {item.subCategoryName}
                        </td>
                        <td className="whitespace-nowrap px-6 py-4 flex flex-row-reverse ">
                          <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/subCategory/update-subCategory/${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="mt-4 flex justify-between sm:px-[2rem] mx-3">
            <button
              className="bg-[#383736] hover:bg-[#FE342B] text-white px-4 py-2 rounded"
              onClick={handlePrevPage}
            >
              Previous
            </button>
            <button
              className="bg-[#383736] hover:bg-[#FE342B] text-white px-4 py-2 rounded"
              onClick={handleNextPage}
            >
              Next
            </button>
          </div>
        </>
      )}
    </div>
  );
};

export default ViewSubCategory;
