import type { Table } from "@tanstack/react-table";
import { createContext, type ReactNode, useContext } from "react";
import type {
	PinnedFiltro,
	SearchFiltro,
} from "~/components/ui/dataTable-toolbar";

type DataTableContextType<TData> = {
	table: Table<TData>;
	searchColumn?: SearchFiltro;
	columns_titles: Record<string, string>;
	pinnedFiltri?: PinnedFiltro[];
	hasSelectRow?: boolean;
};

// biome-ignore lint/suspicious/noExplicitAny: <needeed>
const DataTableContext = createContext<DataTableContextType<any> | null>(null);

export function DataTableProvider<TData>({
	children,
	table,
	searchColumn,
	columns_titles,
	pinnedFiltri,
	hasSelectRow,
}: {
	children: ReactNode;
	table: Table<TData>;
	searchColumn?: SearchFiltro;
	columns_titles: Record<string, string>;
	pinnedFiltri?: PinnedFiltro[];
	hasSelectRow?: boolean;
}) {
	return (
		<DataTableContext.Provider
			value={{
				table,
				searchColumn,
				columns_titles,
				pinnedFiltri,
				hasSelectRow,
			}}
		>
			{children}
		</DataTableContext.Provider>
	);
}

export const useDataTable = <TData,>() => {
	const value = useContext(
		DataTableContext,
	) as DataTableContextType<TData> | null;
	if (!value) {
		throw new Error("useDataTable must be used within a DataTableProvider");
	}
	return value;
};
