import React, { useState } from "react";
import Cookies from "js-cookie";
import Link from "next/link";
import Image from "next/image";
import apiInterceptor from "@/interceptor/interceptor";
import { userActivity } from "@/components/commonFunctions/userActivity";
import { useRouter } from "next/router";
import jwt from "jsonwebtoken";


const ViewCategory = () => {

  
  const token: any = Cookies.get("jazz_admin_token");

  const decodedToken = jwt.decode(token);

  const userId = decodedToken ? decodedToken.sub : null;
  console.log("ADMIN USER ID",userId);
  const [categoryData, setCategoryData] = React.useState<any[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [isLoading, setIsLoading] = useState(true);

  React.useEffect(() => {
    const getCatgeory = async () => {
      try {
        setIsLoading(true);
        const accessToken = Cookies.get("jazz_token");
        const response = await apiInterceptor.get(
          `/api/admin/category?page=${currentPage}`,
          {
            headers: {
              authorization: `Bearer ${accessToken}`,
            },
          }
        );
        setCategoryData(response.data.categories.data);
        setTotalPages(response.data.categories.pagination.total_pages);
      } catch (error) {
        console.error("Error:", error);
      } finally {
        setIsLoading(false);
      }
    };
    getCatgeory();
  }, [currentPage]);

  // const handleDelete = async (categoryId: string) => {
  //   try {
  //     const accessToken = Cookies.get("jazz_token");
  //     await apiInterceptor.delete(`/api/admin/category/${categoryId}`, {
  //       headers: {
  //         authorization: `Bearer ${accessToken}`,
  //       },
  //     });
  //     // Update the state to remove the deleted category
  //     setCategoryData((prevData) =>
  //       prevData.filter((item) => item._id !== categoryId)
  //     );
  //   } 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/category/addCategory"}
        onClick={() => {
          if (userId) {
            userActivity(
              userId,
              "admin",
              "Add New Category",
              {
                pageVisit: `/`,
              },
              navigator.userAgent
            );
          } else {
            console.error("User ID is not available");
          }
        }}
      >
        Add New Category
      </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-[2rem] py-4 text-right">Action</th>
                    </tr>
                  </thead>
                  {categoryData.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="px-6 py-4 ">
                          <Image
                            src={`https://api.jazzagain.com/public/${item.categoryImage}`}
                            width={45}
                            height={45}
                            alt={item.categoryName}
                            className="inline-table mx-2"
                          />
                          {item.categoryName}
                        </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/category/update-category/${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] transition-all duration-300 text-white px-4 py-2 rounded"
              onClick={handlePrevPage}
            >
              Previous
            </button>
            <button
              className="bg-[#383736] hover:bg-[#FE342B] transition-all duration-300 text-white px-4 py-2 rounded"
              onClick={handleNextPage}
            >
              Next
            </button>
          </div>
        </>
      )}
    </div>
  );
};

export default ViewCategory;
