import type { Table } from "@tanstack/react-table";
import {
	createContext,
	type ReactNode,
	useCallback,
	useContext,
	useState,
} from "react";
import type {
	Storageindex,
	StorageindexId,
} from "~/schemas/public/Storageindex";

type TData = {
	id: StorageindexId;
	filename: string | null;
	ext: string | null;
	created_at: Date;
	from_admin: boolean;
	actions: string;
	expires_at: Date | null;
};

export type StorageTable = Table<TData>;

const StorageTableContext = createContext<{
	table: StorageTable | undefined;
	setTable: (table: StorageTable | undefined) => void;
	selectedRows: Storageindex[];
	cb_onStateChange: () => void;
}>({
	table: undefined,

	setTable: () => {},
	selectedRows: [],
	cb_onStateChange: () => {},
});

export const StorageTableProvider = ({ children }: { children: ReactNode }) => {
	const [table, setTable] = useState<StorageTable | undefined>(undefined);

	const [selectedRows, setSelectedRows] = useState<Storageindex[]>([]);

	const cb_onStateChange = useCallback(() => {
		if (table) {
			const rowSelection = table.getState().rowSelection;
			const data = table.getCoreRowModel().rowsById;
			const selected = Object.keys(rowSelection).reduce(
				(acc: TData[], rowId) => {
					const row = data[rowId];
					if (row && rowSelection[rowId]) {
						acc.push(row.original);
					}
					return acc;
				},
				[],
			);
			setSelectedRows(
				selected.map((r) => ({
					id: r.id,
					created_at: r.created_at,
					filename: r.filename,
					ext: r.ext,
					from_admin: r.from_admin,
					expires_at: r.expires_at,
				})),
			);
		}
	}, [table]);

	return (
		<StorageTableContext.Provider
			value={{ table, setTable, selectedRows, cb_onStateChange }}
		>
			{children}
		</StorageTableContext.Provider>
	);
};

export const useStorageTable = () => {
	const context = useContext(StorageTableContext);
	if (!context) {
		throw new Error(
			"useStorageTable must be used within a StorageTableProvider",
		);
	}
	return context;
};
