import { Button, HStack, Text } from '@chakra-ui/react';
import { ChevronLeftIcon, ChevronRightIcon } from '@chakra-ui/icons';

interface PaginationProps {
  currentPage: number;
  totalPages: number;
  onPageChange: (page: number) => void;
  maxVisiblePages?: number;
}

export default function Pagination({
  currentPage,
  totalPages,
  onPageChange,
  maxVisiblePages = 5,
}: PaginationProps) {
  if (totalPages <= 1) return null;

  const getPageNumbers = () => {
    const pages = [];
    let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
    const endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

    if (endPage - startPage + 1 < maxVisiblePages) {
      startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }

    for (let i = startPage; i <= endPage; i++) {
      pages.push(i);
    }

    return pages;
  };

  const pages = getPageNumbers();

  return (
    <HStack spacing={1}>
      <Button
        size="sm"
        variant="outline"
        onClick={() => onPageChange(currentPage - 1)}
        isDisabled={currentPage === 1}
        aria-label="Předchozí stránka"
      >
        <ChevronLeftIcon />
      </Button>

      {!pages.includes(1) && (
        <>
          <Button
            size="sm"
            variant={currentPage === 1 ? 'solid' : 'outline'}
            onClick={() => onPageChange(1)}
          >
            1
          </Button>
          {!pages.includes(2) && <Text>...</Text>}
        </>
      )}

      {pages.map((page) => (
        <Button
          key={page}
          size="sm"
          variant={currentPage === page ? 'solid' : 'outline'}
          colorScheme={currentPage === page ? 'blue' : 'gray'}
          onClick={() => onPageChange(page)}
          aria-current={currentPage === page ? 'page' : undefined}
        >
          {page}
        </Button>
      ))}

      {!pages.includes(totalPages) && (
        <>
          {!pages.includes(totalPages - 1) && <Text>...</Text>}
          <Button
            size="sm"
            variant={currentPage === totalPages ? 'solid' : 'outline'}
            onClick={() => onPageChange(totalPages)}
          >
            {totalPages}
          </Button>
        </>
      )}

      <Button
        size="sm"
        variant="outline"
        onClick={() => onPageChange(currentPage + 1)}
        isDisabled={currentPage === totalPages}
        aria-label="Další stránka"
      >
        <ChevronRightIcon />
      </Button>
    </HStack>
  );
}
