import {
  CaretLeftIcon,
  CaretRightIcon,
  DotsThreeIcon,
} from '@phosphor-icons/react';
import { Button } from './ui/button';
import { ButtonGroup } from './ui/button-group';

type PaginationProps = {
  currentPage: number;
  totalPages: number;
  onPageChange: (page: number) => void;
};

const Pagination = ({
  currentPage,
  totalPages,
  onPageChange,
}: PaginationProps) => {
  const getPageNumbers = () => {
    const pages: (number | string)[] = [];

    if (totalPages <= 5) {
      // Hiển thị tất cả nếu trang ít
      for (let i = 1; i <= totalPages; i++) {
        pages.push(i);
      }
    } else {
      if (currentPage <= 3) {
        pages.push(1, 2, 3, 'dot', totalPages);
      } else if (currentPage >= totalPages - 2) {
        pages.push(1, 'dot', totalPages - 2, totalPages - 1, totalPages);
      } else {
        pages.push(1, 'dot', currentPage, 'dot', totalPages);
      }
    }

    return pages;
  };

  const pages = getPageNumbers();

  return (
    <div className="flex items-center justify-center gap-2">
      <ButtonGroup>
        <ButtonGroup>
          <Button
            variant="outline"
            size="icon-sm"
            disabled={currentPage === 1}
            className="cursor-pointer"
          >
            <CaretLeftIcon />
          </Button>
        </ButtonGroup>
        <ButtonGroup>
          {pages.map((page, idx) =>
            page === 'dot' ? (
              <Button
                variant="outline"
                size="icon-sm"
                key={idx}
                disabled={true}
              >
                <DotsThreeIcon size={14} />
              </Button>
            ) : (
              <Button
                variant="outline"
                key={idx}
                size="icon-sm"
                data-active={currentPage === page}
                onClick={() => onPageChange(Number(page))}
                disabled={currentPage === page}
                className="cursor-pointer"
              >
                {page}
              </Button>
            ),
          )}
        </ButtonGroup>
        <ButtonGroup>
          <Button
            variant="outline"
            size="icon-sm"
            disabled={currentPage === totalPages}
            className="cursor-pointer"
          >
            <CaretRightIcon />
          </Button>
        </ButtonGroup>
      </ButtonGroup>
    </div>
  );
};

export default Pagination;
