import { useTranslations } from "next-intl";

const PaginationPages = ({
  postsPerPage,
  totalPosts,
  paginate,
  currentPage,
} :{
  postsPerPage: number;
  totalPosts: number;
  paginate: (pageNumber: number) => void;
  currentPage: number;
}) => {
  const t = useTranslations("Pagination");

  const totalPages = Math.ceil(totalPosts / postsPerPage);
  if (totalPages <= 1) return null;

  const getVisiblePages = () => {
    let start = Math.max(1, currentPage - 2);
    let end = Math.min(totalPages, currentPage + 2);

    if (currentPage <= 3) {
      start = 1;
      end = Math.min(5, totalPages);
    }

    if (currentPage >= totalPages - 2) {
      end = totalPages;
      start = Math.max(1, totalPages - 4);
    }

    const pages = [];
    for (let i = start; i <= end; i++) {
      pages.push(i);
    }
    return pages;
  };

  const handelNext = () => {
    if (currentPage < totalPages) paginate(currentPage + 1);
  };

  const handelPrev = () => {
    if (currentPage > 1) paginate(currentPage - 1);
  };

  return (
    <div className="flex gap-2 justify-center items-center">
      {/* Previous */}
      <button
        onClick={handelPrev}
        disabled={currentPage === 1}
        className={`border border-gray-300 rounded-md px-4 py-2 cursor-pointer hover:bg-lightPrimary2 hover:text-primary text-dark
          ${
            currentPage === 1
              ? "opacity-50 cursor-not-allowed"
              : "hover:bg-lightPrimary2 hover:text-primary"
          }`}
      >
        {t("Previous")}
      </button>

      {/* Pages */}
      {getVisiblePages().map((number) => (
        <button
          key={number}
          onClick={() => paginate(number)}
          className={`border border-gray-300 rounded-md px-3 md:px-4 py-2 cursor-pointer hover:bg-lightPrimary2 hover:text-primary text-dark
            ${currentPage === number ? "bg-lightPrimary2 text-primary" : ""}`}
        >
          {number}
        </button>
      ))}

      {/* Next */}
      <button
        onClick={handelNext}
        disabled={currentPage === totalPages}
        className={`border border-gray-300 rounded-md px-4 py-2 cursor-pointer hover:bg-lightPrimary2 hover:text-primary text-dark
          ${
            currentPage === totalPages
              ? "opacity-50 cursor-not-allowed"
              : "hover:bg-lightPrimary2 hover:text-primary"
          }`}
      >
        {t("Next")}
      </button>
    </div>
  );
};

export default PaginationPages;
