import type { Table } from "@tanstack/react-table";
import {
	createContext,
	type ReactNode,
	useCallback,
	useContext,
	useState,
} from "react";
import type { FileMetadataWithAdmin } from "~/server/services/storage.service";

type TData = FileMetadataWithAdmin;

export type StorageTable = Table<TData>;

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

	setTable: () => {},
	table: undefined,
});

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

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

	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);
		}
	}, [table]);

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

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