"use client";
import {
    ColumnDef,
    flexRender,
    getCoreRowModel,
    useReactTable,
    getPaginationRowModel,
    SortingState,
    ColumnFiltersState,
    getFilteredRowModel,
  } from "@tanstack/react-table"
import { useState } from "react";
import { clsx, type ClassValue } from "clsx"
import Image from "next/image";
import { icons } from "#/assets/icons";

  interface DataTableProps<TData, TValue> {
    columns: ColumnDef<TData, TValue>[]
    data: TData[],
    pageSize?: number
  }

export default function Table<TData, TValue>({
    columns,
    data,
    pageSize = 10
  }: DataTableProps<TData, TValue>) {
    const [rowSelection, setRowSelection] = useState({})
    const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>(
        []
      )

    const table = useReactTable({
        data,
        columns,
        getCoreRowModel: getCoreRowModel(),
        getPaginationRowModel: getPaginationRowModel(),
    
        state: {
          rowSelection,
          columnFilters,
        },
        initialState: {
            pagination: {
                pageSize: pageSize,
            }
        },
        enableRowSelection: true,
        getFilteredRowModel: getFilteredRowModel(),
        onRowSelectionChange: setRowSelection,
        onColumnFiltersChange: setColumnFilters,
      })

    const totalPages = table.getPageCount()
    const currentPage = table.getState().pagination.pageIndex + 1

    const getPageNumbers = () => {
        const pages = []
        for (let i = 1; i <= totalPages; i++) {
            pages.push(i)
        }
        return pages
    }

    return(
        <div>
            <div className="rounded-lg border border-gray-200">
                <table className="w-full overflow-x-auto rounded-lg " style={{ borderTopLeftRadius: '10px', borderTopRightRadius: '10px', }}>
                    <thead className="h-10">
                        {table.getHeaderGroups().map((headerGroup) => (
                            <tr key={headerGroup.id} className="rounded-lg">
                                <th className="bg-blue-300 p-3 text-start first:rounded-tl-lg">
                                    <input checked={
                                        table.getIsAllPageRowsSelected() ||
                                            (table.getIsSomePageRowsSelected() && undefined)
                                        } 
                                        onChange={(e) => table.toggleAllPageRowsSelected(e.target.checked)} 
                                        type="checkbox" name="" id="" 
                                    />
                                </th>
                                {headerGroup.headers.map((header) => {
                                    return(
                                        <th key={header.id} className="bg-blue-300 p-3 text-start last:rounded-tr-lg">
                                            {flexRender(
                                                header.column.columnDef.header,
                                                header.getContext()
                                            )}
                                        </th>
                                    )
                                })}
                            </tr>
                        ))}
                    </thead>
                    <tbody>
                        {table.getRowModel().rows.length ? (
                            table.getRowModel().rows.map((row) => (
                                <tr key={row.id} className={clsx('hover:bg-gray-300 border-t border-gray-200', { 'bg-gray-300': row.getIsSelected()})}>
                                    <td className="p-3 text-start">
                                        <input 
                                            checked={row.getIsSelected()} 
                                            onChange={(e) => row.toggleSelected(e.target.checked)} 
                                            type="checkbox" name="" id="" 
                                        />
                                    </td>
                                    {row.getVisibleCells().map((cell) => (
                                        <td key={cell.id} className="p-3 text-start">
                                            {flexRender(cell.column.columnDef.cell, cell.getContext())}
                                        </td>
                                    ))}
                                </tr>
                            ))
                        )
                        : (
                            <tr>
                                <td colSpan={columns.length}>
                                    Aucun résultats
                                </td>
                            </tr>
                        )}
                    </tbody>
                </table>
            </div>

            <div className="flex items-center justify-end space-x-2 py-4">
            <button
                className="bg-gray-100 shadow-xs hover:bg-gray-300 px-3 py-1 rounded w-9 h-9"
                onClick={() => table.previousPage()}
                disabled={!table.getCanPreviousPage()}
            >
                <Image alt="" src={icons.arrowLeft} className="hover:text-blue-400"/>
            </button>

            <div className="flex space-x-1">
                {getPageNumbers().map((pageNumber) => (
                    <button
                        key={pageNumber}
                        className={clsx(
                            "px-3 py-1 rounded w-9 h-9",
                            pageNumber === currentPage 
                                ? "bg-[#E9F0FF] text-blue-400"
                                : "bg-gray-100 hover:bg-gray-300"
                        )}
                        onClick={() => table.setPageIndex(pageNumber - 1)}
                    >
                        {pageNumber}
                    </button>
                ))}
            </div>

            <button
                className="w-9 h-9 bg-gray-100 shadow-xs hover:bg-gray-300 hover:text-black px-3 py-1 rounded"
                onClick={() => table.nextPage()}
                disabled={!table.getCanNextPage()}
            >
                <Image alt="" src={icons.arrowRight} />
            </button>
        </div>
        </div>
    )
}