import { Flex, chakra, IconButton, Text, Select, Box } from "@chakra-ui/react";
import { Table as ReactTable } from "@tanstack/react-table";
import {
  BiChevronLeft,
  BiChevronsLeft,
  BiChevronRight,
  BiChevronsRight,
} from "react-icons/bi";
import { TData, pageLimitOptions } from "../types";

export const DataTablePagination = <T extends TData>({
  table,
}: {
  table: ReactTable<T>;
}) => (
  <PaginationContainer>
    <PaginationButton
      aria-label="First Page"
      size="xs"
      icon={<BiChevronsLeft />}
      onClick={() => table.setPageIndex(0)}
      isDisabled={!table.getCanPreviousPage()}
    />
    <PaginationButton
      aria-label="Previous Page"
      size="xs"
      icon={<BiChevronLeft />}
      onClick={() => table.previousPage()}
      isDisabled={!table.getCanPreviousPage()}
    />

    <PageText>
      Page {table.getState().pagination.pageIndex + 1} of {table.getPageCount()}
    </PageText>

    <PaginationButton
      aria-label="Next Page"
      size="xs"
      icon={<BiChevronRight />}
      onClick={() => table.nextPage()}
      isDisabled={!table.getCanNextPage()}
    />
    <PaginationButton
      aria-label="Last Page"
      size="xs"
      icon={<BiChevronsRight />}
      onClick={() => table.setPageIndex(table.getPageCount() - 1)}
      isDisabled={!table.getCanNextPage()}
    />

    <Box w="20px" />

    <PageText>Page Size:</PageText>
    <Flex maxW="80px">
      <PageSelect
        size="xs"
        value={table.getState().pagination.pageSize}
        onChange={(e) => table.setPageSize(Number(e.target.value))}
      >
        {pageLimitOptions.map((value) => (
          <option key={value} value={value}>
            {value}
          </option>
        ))}
      </PageSelect>
    </Flex>
  </PaginationContainer>
);

const PaginationContainer = chakra(Flex, {
  baseStyle: {
    gap: "5px",
    alignItems: "center",
  },
});

const PaginationButton = chakra(IconButton, {
  baseStyle: {
    rounded: "lg",
  },
});

const PageText = chakra(Text, {
  baseStyle: {
    fontSize: "sm",
    userSelect: "none",
  },
});

const PageSelect = chakra(Select, {
  baseStyle: {
    rounded: "lg",
  },
});
