import { Button } from '@/components/ui/button';
import { Table } from '@tanstack/react-table';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { useSearchParams } from 'next/navigation';
import { useRouter } from 'next/navigation';
import React from 'react';

interface DataTablePaginationProps {
  table: Table<any>;
  totalPage: number; // Total jumlah halaman
  totalData: number; // Total jumlah data
  visiblePageCount?: number; // Jumlah halaman yang ditampilkan (default 5)
}

const TablePagination = ({ table, totalPage, totalData, visiblePageCount = 5 }: DataTablePaginationProps) => {
  const router = useRouter();
  const searchParams = useSearchParams();

  const [currentPageIndex, setCurrentPageIndex] = React.useState<number>(1);

  React.useEffect(() => {
    const pageFromUrl = searchParams?.get('page');
    if (pageFromUrl) {
      setCurrentPageIndex(Number(pageFromUrl));
    }
  }, [searchParams]);

  // Hitung startPage dan endPage, disesuaikan untuk dimulai dari 1
  const startPage = Math.max(1, currentPageIndex - Math.floor(visiblePageCount / 2));
  const endPage = Math.min(totalPage, startPage + visiblePageCount - 1);

  const handlePageChange = (pageIndex: number) => {
    // Perbarui query parameter di URL
    const searchParams = new URLSearchParams(window.location.search);
    searchParams.set('page', (pageIndex).toString()); // Menyimpan halaman sebagai 1-based index
    router.push(`${window.location.pathname}?${searchParams.toString()}`);

    // Pindahkan halaman di tabel
    table.setPageIndex(pageIndex);
    setCurrentPageIndex(pageIndex + 1); // Update state untuk halaman saat ini
  };

  return (
    <div className="flex items-center justify-end py-4 px-10">
      <div className="flex-1 text-sm text-muted-foreground">
        {table.getFilteredSelectedRowModel().rows.length} of{" "}
        {totalData} row(s) selected.
      </div>
      <div className="flex items-center gap-2 flex-none">
        <Button
          variant="outline"
          size="icon"
          onClick={() => handlePageChange(1)}
          disabled={currentPageIndex === 1}
          className='w-8 h-8'
        >
          <ChevronLeft className='w-4 h-4' />
        </Button>
        {Array.from({ length: endPage - startPage + 1 }, (_, index) => startPage + index).map((pageIndex) => (
          <Button
            key={`page-${pageIndex}`}
            onClick={() => handlePageChange(pageIndex)}
            size="icon"
            className="w-8 h-8"
            variant={currentPageIndex === pageIndex ? 'default' : 'outline'}
          >
            {pageIndex}
          </Button>
        ))}
        <Button
          variant="outline"
          size="icon"
          onClick={() => handlePageChange(totalPage)}
          disabled={currentPageIndex === totalPage}
          className='w-8 h-8'
        >
          <ChevronRight className='w-4 h-4' />
        </Button>
      </div>
    </div>
  );
};

export default TablePagination;
