import { ChevronLeft, ChevronRight } from 'lucide-react';
import { cn } from '../lib/utils';

interface PaginationProps {
  page: number;
  totalPages: number;
  onPageChange: (page: number) => void;
  hasNext?: boolean;
  hasPrev?: boolean;
}

export default function Pagination({
  page,
  totalPages,
  onPageChange,
  hasNext,
  hasPrev,
}: PaginationProps) {
  const canPrev = hasPrev ?? page > 1;
  const canNext = hasNext ?? page < totalPages;

  const getPageNumbers = () => {
    const pages: (number | '...')[] = [];
    const delta = 2;

    for (let i = 1; i <= totalPages; i++) {
      if (
        i === 1 ||
        i === totalPages ||
        (i >= page - delta && i <= page + delta)
      ) {
        pages.push(i);
      } else if (pages[pages.length - 1] !== '...') {
        pages.push('...');
      }
    }

    return pages;
  };

  return (
    <nav aria-label="Pagination" className="flex items-center justify-center gap-1">
      <button
        onClick={() => onPageChange(page - 1)}
        disabled={!canPrev}
        aria-label="Go to previous page"
        className={cn(
          'p-2 rounded-lg transition-colors',
          canPrev
            ? 'hover:bg-gray-800 text-gray-300'
            : 'text-gray-600 cursor-not-allowed'
        )}
      >
        <ChevronLeft size={20} />
      </button>

      <div className="flex items-center gap-1">
        {getPageNumbers().map((p, i) =>
          p === '...' ? (
            <span key={`ellipsis-${i}`} className="px-2 text-gray-500">
              ...
            </span>
          ) : (
            <button
              key={p}
              onClick={() => onPageChange(p)}
              aria-label={`Go to page ${p}`}
              aria-current={p === page ? 'page' : undefined}
              className={cn(
                'min-w-[36px] h-9 rounded-lg text-sm font-medium transition-colors',
                p === page
                  ? 'bg-synor-600 text-white'
                  : 'hover:bg-gray-800 text-gray-400'
              )}
            >
              {p}
            </button>
          )
        )}
      </div>

      <button
        onClick={() => onPageChange(page + 1)}
        disabled={!canNext}
        aria-label="Go to next page"
        className={cn(
          'p-2 rounded-lg transition-colors',
          canNext
            ? 'hover:bg-gray-800 text-gray-300'
            : 'text-gray-600 cursor-not-allowed'
        )}
      >
        <ChevronRight size={20} />
      </button>
    </nav>
  );
}
