import React, { useState, useEffect } from "react";
import apiInterceptor from "@/interceptor/interceptor";
import Cookies from "js-cookie";
import Link from "next/link";
import Image from "next/image";
import { userActivity } from "@/components/commonFunctions/userActivity";
import { useRouter } from "next/router";
import jwt from "jsonwebtoken";

const ViewBrands = () => {
  
  const token: any = Cookies.get("jazz_admin_token");

  const decodedToken = jwt.decode(token);

  const userId = decodedToken ? decodedToken.sub : null;

  const router = useRouter();

  const [brandNames, setBrandNames] = useState<any[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const getBrands = async () => {
      try {
        setIsLoading(true);
        const accessToken = Cookies.get("jazz_token");
        const response = await apiInterceptor.get(
          `/api/admin/brands?page=${currentPage}`,
          {
            headers: {
              authorization: `Bearer ${accessToken}`,
            },
          }
        );
        setBrandNames(response.data.brands.data);
        setTotalPages(response.data.brands.pagination.total_pages);
      } catch (error) {
        console.error("Error:", error);
      } finally {
        setIsLoading(false);
      }
    };
    getBrands();
  }, [currentPage]);

  const handleDelete = async (brandId: string) => {
    try {
      const accessToken = Cookies.get("jazz_token");
      await apiInterceptor.delete(`/api/admin/brands/${brandId}`, {
        headers: {
          authorization: `Bearer ${accessToken}`,
        },
      });
      setBrandNames((prevData) =>
        prevData.filter((item) => item._id !== brandId)
      );
    } catch (error) {
      console.error("Error Deleting Brand:", error);
    }
  };

  const handleNextPage = () => {
    if (currentPage < totalPages) {
      setCurrentPage(currentPage + 1);
    }
  };

  const handlePrevPage = () => {
    if (currentPage > 1) {
      setCurrentPage(currentPage - 1);
    }
  };

  return (
    <div className="flex flex-col p-3">
      <Link
        href={"/admin/brand/addBrand"}
        className="ml-[4rem] lg:ml-4 px-3 mx-4 rounded transition-all duration-300 py-2 hover:bg-[#FE342B] bg-[#383736] max-w-fit text-white my-2"
        onClick={() => {
          if (userId) {
            userActivity(
              userId,
              "admin",
              "Add New Brand",
              {
                pageVisit: `/`,
              },
              navigator.userAgent
            );
          } else {
            console.error("User ID is not available");
          }
        }}
      >
        Add New Brand
      </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 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">BRANDS</th>
                      <th className=" py-4 text-right px-[2rem]">Action</th>
                    </tr>
                  </thead>
                  <tbody>
                    {brandNames.map((item, index) => (
                      <tr
                        key={item._id}
                        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.brandName}
                        </td>
                        <td className="whitespace-nowrap px-6 py-4 flex-row-reverse flex">
                          <button
                            className="bg-[#FE342B] hover:bg-[#d13931] rounded text-white px-3 py-2 mx-2"
                            onClick={() => handleDelete(item._id)}
                          >
                            Delete
                          </button>
                          <Link
                            href={`/admin/brand/update-brand/${item._id}`}
                            className="bg-[#383736] hover:bg-[#2d2d2c] rounded text-white px-3 py-2 mx-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 transition-all duration-300"
              onClick={handlePrevPage}
            >
              Previous
            </button>
            <button
              className="bg-[#383736] hover:bg-[#FE342B] text-white px-4 py-2 rounded transition-all duration-300"
              onClick={handleNextPage}
            >
              Next
            </button>
          </div>
        </>
      )}
    </div>
  );
};

export default ViewBrands;