import { RotateCcw } from "lucide-react";
import type { ComponentType } from "react";
import { Button } from "~/components/ui/button";
import { DataTableFacetedFilter } from "~/components/ui/dataTable-FacetedFilter";
import { DataTableViewOptions } from "~/components/ui/dataTable-ViewToggle";
import Input from "~/components/ui/input";
import { useDataTable } from "~/providers/DataTableProvider";

export type PinnedFiltro = {
	title: string;
	columnName: string;
	options: {
		label: string;
		value: string;
		icon?: ComponentType<{ className?: string }>;
	}[];
};
/**
 * columnName: null per ricerca globale
 */
export type SearchFiltro = {
	columnName: string | null;
	placeholder: string;
};
export function DataTableToolbar<TData>() {
	const { table, pinnedFiltri } = useDataTable<TData>();
	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">
				<SearchInput />
				{pinnedFiltri?.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 />
		</div>
	);
}

function SearchInput<TData>() {
	const { table, searchColumn } = useDataTable<TData>();
	const { globalFilter } = table.getState();
	if (!searchColumn) return null;
	const { columnName, placeholder } = searchColumn;
	if (columnName) {
		return (
			<Input
				className="mt-0 h-8 w-37.5"
				name={columnName}
				onChange={(event) =>
					table.getColumn(columnName)?.setFilterValue(event.target.value)
				}
				placeholder={placeholder}
				value={(table.getColumn(columnName)?.getFilterValue() as string) ?? ""}
			/>
		);
	}
	return (
		<Input
			className="mt-0 h-8 w-37.5"
			name="globalSearch"
			onChange={(event) => table.setGlobalFilter(String(event.target.value))}
			placeholder={searchColumn.placeholder}
			value={globalFilter ?? ""}
		/>
	);
}
