import React, { useState, useEffect } from "react";
import axios from "axios";
import { useRouter } from "next/router";
import Image from "next/image";

type Product = {
    _id: string;
    productFeaturedImage: string;
    productTitle: string;
    categoryId: string;
    subCategoryId: string;
    productSellingPrice: number;
    updated_at: string;
    seller: {
        firstName: string;
    };
};

type Category = {
    _id: string; // Ensure _id is included
    categoryName: string;
};

const categories: Record<string, Category> = {
    'category1': { _id: 'category1', categoryName: 'Category 1' },
    'category2': { _id: 'category2', categoryName: 'Category 2' },
};

const subCategories: Record<string, { subCategoryName: string }> = {
    'subCategory1': { subCategoryName: 'Subcategory 1' },
    'subCategory2': { subCategoryName: 'Subcategory 2' },
};

const Index = () => {
    const [data, setData] = useState<Product[] | null>(null);
    const [loading, setLoading] = useState<boolean>(true);
    const [error, setError] = useState<Error | null>(null);
    const [currentPage, setCurrentPage] = useState<number>(1);
    const productsPerPage = 10;

    const router = useRouter();
    const { id } = router.query;

    useEffect(() => {
        const fetchData = async () => {
            try {
                setLoading(true);
                const response = await axios.get(
                    `https://api.jazzagain.com/public/index.php/api/moreBySeller/${id}`
                );
                setData(response.data);
            } catch (err) {
                setError(err instanceof Error ? err : new Error("Unknown error occurred."));
            } finally {
                setLoading(false);
            }
        };
        if (id) fetchData();
    }, [id]);

  const handlePrevPage = () => {
    if (currentPage > 1) setCurrentPage(currentPage - 1);
  };

  const handleNextPage = () => {
    if (data && currentPage * productsPerPage < data.length) {
      setCurrentPage(currentPage + 1);
    }
  };

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  const paginatedData = data
    ? data.slice((currentPage - 1) * productsPerPage, currentPage * productsPerPage)
    : [];

  return (
    <div>
      <div className="my-4 text-center">
        <h2 className="text-2xl font-semibold text-[#FE342B]">Total Products: {data ? data.length : 0}</h2>
      </div>

      <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">CATEGORY</th>
                <th className="px-6 py-4">SUBCATEGORY</th>
                <th className="px-6 py-4">SELLING PRICE</th>
                <th className="px-6 py-4">UPLOAD DATE</th>
                <th className="px-6 py-4">SELLER NAME</th>
              </tr>
            </thead>

            {paginatedData.length > 0 ? (
              <tbody>
                {paginatedData.map((item, index) => (
                  <tr
                    key={item._id}
                    className="border-b bg-neutral-10 dark:border-neutral-500 hover:bg-gray-200"
                  >
                    <td className="px-6 py-1 font-medium">
                      {(currentPage - 1) * productsPerPage + index + 1}
                    </td>
                    <td className=" px-6 py-1">
                      <Image
                        src={`https://api.jazzagain.com/public/${item.productFeaturedImage}`}
                        height={60}
                        width={60}
                        alt={item.productTitle}
                      />
                    </td>
                    <td className="px-6 py-1">{item.productTitle}</td>
                    <td className="px-6 py-1">
                      {categories[item.categoryId]?.categoryName || "-"}
                    </td>
                    <td className="px-6 py-1">
                      {subCategories[item.subCategoryId]?.subCategoryName || "-"}
                    </td>
                    <td className="px-6 py-1">{item.productSellingPrice}</td>
                    <td className="px-6 py-1">
                      {new Date(item.updated_at).toLocaleDateString("en-US", {
                        year: "numeric",
                        month: "long",
                        day: "numeric",
                      })}
                    </td>
                    <td className="px-6 py-1">{item.seller.firstName}</td>
                  </tr>
                ))}
              </tbody>
            ) : (
              <tbody>
                <tr>
                  <td colSpan={9} className="text-center px-6 py-4">
                    No products found.
                  </td>
                </tr>
              </tbody>
            )}
          </table>
        </div>
      </div>

      <div className="mx-3 my-4 flex justify-between sm:px-[2rem]">
        <button
          onClick={handlePrevPage}
          disabled={loading || currentPage === 1}
          className={`${
            currentPage === 1 ? "bg-gray-300" : "bg-[#383736] hover:bg-[#FE342B]"
          } text-white px-4 py-2 rounded`}
        >
          Previous
        </button>
        <button
          onClick={handleNextPage}
          disabled={loading || !(data && currentPage * productsPerPage < data.length)}
          className={`${
            data && currentPage * productsPerPage >= data.length
              ? "bg-gray-300"
              : "bg-[#383736] hover:bg-[#FE342B]"
          } text-white px-4 py-2 rounded`}
        >
          Next
        </button>
      </div>
    </div>
  );
};

export default Index;
