import React from "react";

const Pagination = ({ totalPages, currentPage, onPageChange }) => {
  if (!totalPages || totalPages <= 1) return null;

  const handlePageClick = (page) => {
    if (page >= 1 && page <= totalPages) onPageChange(page);
  };

  const getPageNumbers = () => {
    const pages = [];
    if (totalPages <= 7) {
      for (let i = 1; i <= totalPages; i++) pages.push(i);
    } else {
      pages.push(1);
      let start = Math.max(currentPage - 2, 2);
      let end = Math.min(currentPage + 2, totalPages - 1);

      if (start > 2) pages.push("...");
      for (let i = start; i <= end; i++) pages.push(i);
      if (end < totalPages - 1) pages.push("...");
      pages.push(totalPages);
    }
    return pages;
  };

  const pages = getPageNumbers();

  return (
    <div className="flex flex-row-reverse justify-center items-center mt-5">
      <button
        onClick={() => handlePageClick(currentPage - 1)}
        className="px-4 py-2 bg-[#1f5f79] text-white rounded-l-md"
        disabled={currentPage === 1}
      >
        قبلی
      </button>

      {pages.map((page, idx) =>
        page === "..." ? (
          <span key={idx} className="px-3 text-white">...</span>
        ) : (
          <button
            key={idx}
            onClick={() => handlePageClick(page)}
            className={`px-4 py-2 mx-1 rounded-md ${
              page === currentPage
                ? "bg-[#247392] text-white"
                : "bg-[#252525] text-white hover:bg-[#678fa062]"
            }`}
          >
            {page}
          </button>
        )
      )}

      <button
        onClick={() => handlePageClick(currentPage + 1)}
        className="px-4 py-2 bg-[#1f5f79] text-white rounded-r-md"
        disabled={currentPage === totalPages}
      >
        بعدی
      </button>
    </div>
  );
};

export default Pagination;
