"use client";
import fetchData from "@/api/fetch-data";
import Loading from "@/app/loading";
import AlertWarning from "@/app/ui/shared/AlertWarning";
import CustomBreadcrumb from "@/app/ui/shared/CustomBreadcrumb";
import ProductCard from "@/app/ui/shared/ProductCard";
import { useTranslations } from "next-intl";
import { useEffect, useState } from "react";

export default function BrandProducts({ params: { id } }) {
  const [products, setProducts] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [loading, setLoading] = useState(true);
  const [error, setErorr] = useState(null);
  const t = useTranslations("filter");
  const [brandName, setBrandName] = useState("");

  // function to fetch brands products
  async function fetchBrandProducts() {
    setLoading(true);
    const response = await fetchData({
      endPoint: `/brands/${id}?page=${currentPage}`,
    });
    if (!response.error) {
      if (
        response.status == "success" &&
        response?.data?.products?.data.length > 0
      ) {
        setBrandName(response?.data?.brand?.name);
        setProducts(response?.data?.products?.data);
        setTotalPages(response?.data?.products?.last_page);
      }
      setLoading(false);
    } else {
      setErorr(response.message);
    }
  }
  // useffect to fetch products
  useEffect(() => {
    fetchBrandProducts();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentPage]);

  //  function to handle pagination
  const handlePagination = (page) => {
    if (page >= 1 && page <= totalPages) {
      setCurrentPage(page);
    }
  };
  // loading
  if (loading) {
    return (
      <div>
        <Loading />
      </div>
    );
  }
  // show no products alert
  if (products.length === 0) {
    return (
      <div className="py-8">
        <AlertWarning text={t("noproducts")} />
      </div>
    );
  }

  // show error alert
  if (error) {
    return (
      <div className="py-8">
        <AlertWarning text={error} />
      </div>
    );
  }

  // show products layout
  if (products.length > 0) {
    return (
      <>
        <CustomBreadcrumb route={brandName} subs={true} />
        <div className="container  grid grid-cols-12  gap-2 md:gap-4  my-4">
          {/* product layout */}
          {products.map((item) => (
            <div
              key={item.id}
              className="lg:col-span-3  md:col-span-4 col-span-6"
            >
              <ProductCard product={item} />
            </div>
          ))}
          {/* paginatio control */}
          <div className="col-span-12">
            <div className="flex justify-center gap-4 items-center my-10  w-full">
              <button
                onClick={() => handlePagination(currentPage + 1)}
                disabled={currentPage === totalPages}
                className={`px-4 py-2 bg-main text-white rounded ${
                  currentPage === totalPages
                    ? "cursor-not-allowed bg-main/35 "
                    : ""
                }`}
              >
                {t("next")}
              </button>
              <p className="text-gray-400">
                {t("page")} {currentPage} {t("from")} {totalPages}
              </p>
              <button
                onClick={() => handlePagination(currentPage - 1)}
                disabled={currentPage === 1}
                className={`px-4 py-2 bg-main text-white rounded ${
                  currentPage == 1 ? "cursor-not-allowed bg-main/35 " : ""
                }`}
              >
                {t("prev")}
              </button>
            </div>
          </div>
        </div>
      </>
    );
  }
}
