import type { Table } from '@tanstack/react-table';
import { ChevronLeftIcon, ChevronRightIcon } from '@radix-ui/react-icons';
import type * as React from 'react';
import { Icons } from '@/components/icons';
import { Button } from '@/components/ui/button';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import { cn } from '@/lib/utils';

export interface DataTablePaginationProps<TData> extends React.ComponentProps<'div'> {
  table: Table<TData>;
  pageSizeOptions?: number[];
  labels?: {
    total?: (count: number) => string;
    selected?: (selected: number, total: number) => string;
    rowsPerPage?: string;
    page?: (page: number, pageCount: number) => string;
    firstPage?: string;
    previousPage?: string;
    nextPage?: string;
    lastPage?: string;
  };
}

export function DataTablePagination<TData>({
  table,
  pageSizeOptions = [10, 20, 30, 40, 50],
  labels,
  className,
  ...props
}: DataTablePaginationProps<TData>) {
  const selectedCount = table.getFilteredSelectedRowModel().rows.length;
  const filteredCount = table.getFilteredRowModel().rows.length;
  const pageIndex = table.getState().pagination.pageIndex + 1;
  const pageCount = table.getPageCount();

  return (
    <div
      className={cn(
        'flex w-full min-w-0 flex-wrap items-center justify-between gap-4 p-1',
        className
      )}
      {...props}
    >
      <div className='text-muted-foreground min-w-0 text-sm'>
        {selectedCount > 0
          ? (labels?.selected?.(selectedCount, filteredCount) ??
            `เลือกแล้ว ${selectedCount} จาก ${filteredCount} รายการ`)
          : (labels?.total?.(filteredCount) ?? `${filteredCount.toLocaleString('th-TH')} รายการ`)}
      </div>
      <div className='flex w-full min-w-0 flex-wrap items-center justify-between gap-4 sm:w-auto sm:justify-end'>
        <div className='flex min-w-0 items-center gap-2'>
          <p className='text-sm font-medium whitespace-nowrap'>
            {labels?.rowsPerPage ?? 'จำนวนต่อหน้า'}
          </p>
          <Select
            value={`${table.getState().pagination.pageSize}`}
            onValueChange={(value) => {
              table.setPageSize(Number(value));
            }}
          >
            <SelectTrigger
              aria-label={labels?.rowsPerPage ?? 'จำนวนต่อหน้า'}
              className='h-8 w-[4.5rem] [&[data-size]]:h-8'
            >
              <SelectValue placeholder={table.getState().pagination.pageSize} />
            </SelectTrigger>
            <SelectContent side='top'>
              {pageSizeOptions.map((pageSize) => (
                <SelectItem key={pageSize} value={`${pageSize}`}>
                  {pageSize}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
        <div className='text-sm font-medium whitespace-nowrap'>
          {labels?.page?.(pageIndex, pageCount) ?? `${pageIndex} / ${pageCount}`}
        </div>
        <div className='flex flex-wrap items-center gap-1'>
          <Button
            aria-label={labels?.firstPage ?? 'Go to first page'}
            variant='outline'
            size='icon'
            className='hidden size-8 lg:flex'
            onClick={() => table.setPageIndex(0)}
            disabled={!table.getCanPreviousPage()}
          >
            <Icons.chevronsLeft />
          </Button>
          <Button
            aria-label={labels?.previousPage ?? 'Go to previous page'}
            variant='outline'
            size='icon'
            className='size-8'
            onClick={() => table.previousPage()}
            disabled={!table.getCanPreviousPage()}
          >
            <ChevronLeftIcon />
          </Button>
          <Button
            aria-label={labels?.nextPage ?? 'Go to next page'}
            variant='outline'
            size='icon'
            className='size-8'
            onClick={() => table.nextPage()}
            disabled={!table.getCanNextPage()}
          >
            <ChevronRightIcon />
          </Button>
          <Button
            aria-label={labels?.lastPage ?? 'Go to last page'}
            variant='outline'
            size='icon'
            className='hidden size-8 lg:flex'
            onClick={() => table.setPageIndex(table.getPageCount() - 1)}
            disabled={!table.getCanNextPage()}
          >
            <Icons.chevronsRight />
          </Button>
        </div>
      </div>
    </div>
  );
}
