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 <= 6) {
      // 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, 4, 'dot', totalPages);
      } else if (currentPage >= totalPages - 2) {
        pages.push(
          1,
          'dot',
          totalPages - 3,
          totalPages - 2,
          totalPages - 1,
          totalPages,
        );
      } else {
        pages.push(
          1,
          'dot',
          currentPage - 1,
          currentPage,
          currentPage + 1,
          '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}
            onClick={() => onPageChange(Number(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}
                data-dot={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}
            onClick={() => onPageChange(Number(currentPage + 1))}
            className="cursor-pointer"
          >
            <CaretRightIcon />
          </Button>
        </ButtonGroup>
      </ButtonGroup>
    </div>
  );
};

export default Pagination;
