import { ChevronLeft, ChevronRight } from 'lucide-react';

export default function Pagination({ currentPage, totalPages, basePath, onPageChange }) {
  if (totalPages <= 1) return null;

  const getPages = () => {
    const pages = [];
    const maxVisible = 5;
    let start = Math.max(1, currentPage - Math.floor(maxVisible / 2));
    let end = Math.min(totalPages, start + maxVisible - 1);
    if (end - start < maxVisible - 1) start = Math.max(1, end - maxVisible + 1);
    for (let i = start; i <= end; i++) pages.push(i);
    return pages;
  };

  const buildUrl = (page) => {
    const sep = basePath.includes('?') ? '&' : '?';
    return `${basePath}${sep}page=${page}`;
  };

  const handlePageClick = (e, page) => {
    if (onPageChange) {
      e.preventDefault();
      onPageChange(page);
    }
  };

  return (
    <div className="flex items-center justify-center gap-2 py-8">
      {currentPage > 1 && (
        <a
          href={buildUrl(currentPage - 1)}
          onClick={(e) => handlePageClick(e, currentPage - 1)}
          className="flex h-9 w-9 items-center justify-center rounded-md bg-[#1a1a1a] text-gray-300 hover:bg-[#e50914] hover:text-white transition-colors"
        >
          <ChevronLeft size={16} />
        </a>
      )}

      {getPages().map((page) => (
        <a
          key={page}
          href={buildUrl(page)}
          onClick={(e) => handlePageClick(e, page)}
          className={`flex h-9 min-w-[36px] items-center justify-center rounded-md px-2 text-sm font-medium transition-colors ${
            page === currentPage
              ? 'bg-[#e50914] text-white'
              : 'bg-[#1a1a1a] text-gray-300 hover:bg-[#2a2a2a] hover:text-white'
          }`}
        >
          {page}
        </a>
      ))}

      {currentPage < totalPages && (
        <a
          href={buildUrl(currentPage + 1)}
          onClick={(e) => handlePageClick(e, currentPage + 1)}
          className="flex h-9 w-9 items-center justify-center rounded-md bg-[#1a1a1a] text-gray-300 hover:bg-[#e50914] hover:text-white transition-colors"
        >
          <ChevronRight size={16} />
        </a>
      )}
    </div>
  );
}
