import type { Table } from "@tanstack/react-table";
import { RotateCcw } from "lucide-react";
import type { ComponentType } from "react";
import { DataTableFacetedFilter } from "~/components/custom_ui/dataTable-FacetedFilter";
import { DataTableViewOptions } from "~/components/custom_ui/dataTable-ViewToggle";
import Input from "~/components/custom_ui/input";
import { Button } from "~/components/ui/button";

export type PinnedFiltro = {
	title: string;
	columnName: string;
	options: {
		label: string;
		value: string;
		icon?: ComponentType<{ className?: string }>;
	}[];
};
export type SearchFiltro = {
	columnName: string;
	placeholder: string;
};
export function DataTableToolbar<TData>(props: {
	table: Table<TData>;
	pinnedColumns?: PinnedFiltro[];
	searchColumn?: SearchFiltro;
	columns_titles: Record<string, string>;
	globalFilter: string;
}) {
	const { table, pinnedColumns, searchColumn, columns_titles, globalFilter } =
		props;
	const isFiltered = table.getState().columnFilters.length > 0;

	return (
		<div className="flex items-center justify-between">
			<div className="flex flex-1 flex-wrap items-center gap-2">
				{searchColumn &&
					(searchColumn.columnName ? (
						<Input
							className="mt-0 h-8 w-[150px]"
							onChange={(event) =>
								table
									.getColumn(searchColumn.columnName)
									?.setFilterValue(event.target.value)
							}
							placeholder={searchColumn.placeholder}
							value={
								(table
									.getColumn(searchColumn.columnName)
									?.getFilterValue() as string) ?? ""
							}
						/>
					) : (
						<Input
							className="mt-0 h-8 w-[150px]"
							onChange={(event) =>
								table.setGlobalFilter(String(event.target.value))
							}
							placeholder={searchColumn.placeholder}
							value={globalFilter ?? ""}
						/>
					))}
				{pinnedColumns?.map(
					(column) =>
						table.getColumn(column.columnName) && (
							<DataTableFacetedFilter
								column={table.getColumn(column.columnName)}
								key={column.columnName}
								options={column.options}
								title={column.title}
							/>
						),
				)}

				{isFiltered && (
					<Button
						className="h-8 px-2 lg:px-3"
						onClick={() => table.resetColumnFilters()}
						variant="ghost"
					>
						Reset
						<RotateCcw className="ml-2 size-4" />
					</Button>
				)}
			</div>
			<DataTableViewOptions columns_titles={columns_titles} table={table} />
		</div>
	);
}
