import { FiltersMap } from '@wix/bex-core';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import { useCallback } from 'react';
import { TableFoldersState } from '../state/TableFoldersState';
import { CollectionFoldersBaseConfig } from './CollectionFoldersBaseConfig';
import { useOptionalCachedState } from './useOptionalCachedState';

export interface TableFoldersConfig<
  T1,
  F1 extends FiltersMap,
  T2,
  F2 extends FiltersMap,
> extends CollectionFoldersBaseConfig<T1, F1, T2, F2> {}

export type TableFoldersFactory = <
  T1,
  F1 extends FiltersMap,
  T2,
  F2 extends FiltersMap,
>(
  config: TableFoldersConfig<T1, F1, T2, F2>,
) => TableFoldersState<T1, F1, T2, F2>;

export function useCreateTableFolders() {
  const container = useWixPatternsContainer();

  return useCallback<TableFoldersFactory>(({ items, folders }) => {
    return new TableFoldersState({
      items,
      folders,
      container,
    });
  }, []);
}

export function useTableFolders<
  T1,
  F1 extends FiltersMap,
  T2,
  F2 extends FiltersMap,
>(config: TableFoldersConfig<T1, F1, T2, F2>) {
  const createGridFolders = useCreateTableFolders();

  const state = useOptionalCachedState(() =>
    createGridFolders<T1, F1, T2, F2>(config),
  );

  return state;
}
