import {useListSearch} from "@/hooks/useListSearch";
import usePagination from "@/hooks/usePagination";
import {Column, flexRender, getCoreRowModel, getSortedRowModel, useReactTable} from "@tanstack/react-table";
import clsx from "clsx";
import {useMemo, useState} from "react";
import Button from "./Low/Button";

const SIZE = 25;

export default function List<T>({
	data,
	columns,
	searchFields = [],
	pageSize = SIZE,
}: {
	data: T[];
	columns: any[];
	searchFields?: string[][];
	pageSize?: number;
}) {
	const {rows, renderSearch} = useListSearch(searchFields, data);

	const {items, page, renderMinimal} = usePagination(rows, pageSize);

	const table = useReactTable({
		data: items,
		columns: columns,
		getCoreRowModel: getCoreRowModel(),
		getSortedRowModel: getSortedRowModel(),
	});

	return (
		<div className="w-full h-full flex flex-col gap-6">
			<div className={clsx("w-full flex items-center gap-4", searchFields.length === 0 && "justify-end")}>
				{searchFields.length > 0 && renderSearch()}
				{renderMinimal()}
			</div>

			<table className="rounded-xl bg-mti-purple-ultralight/40 w-full">
				<thead>
					{table.getHeaderGroups().map((headerGroup) => (
						<tr key={headerGroup.id}>
							{headerGroup.headers.map((header) => (
								<th key={header.id} colSpan={header.colSpan}>
									{header.isPlaceholder ? null : (
										<>
											<div
												{...{
													className: header.column.getCanSort()
														? "cursor-pointer select-none py-4 text-left first:pl-4"
														: "",
													onClick: header.column.getToggleSortingHandler(),
												}}>
												{flexRender(header.column.columnDef.header, header.getContext())}
												{{
													asc: " 🔼",
													desc: " 🔽",
												}[header.column.getIsSorted() as string] ?? null}
											</div>
										</>
									)}
								</th>
							))}
						</tr>
					))}
				</thead>
				<tbody className="px-2">
					{table.getRowModel().rows.map((row) => (
						<tr className="odd:bg-white even:bg-mti-purple-ultralight/40 rounded-lg py-2" key={row.id}>
							{row.getVisibleCells().map((cell) => (
								<td className="px-4 py-2" key={cell.id}>
									{flexRender(cell.column.columnDef.cell, cell.getContext())}
								</td>
							))}
						</tr>
					))}
				</tbody>
			</table>
		</div>
	);
}
