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

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

export type GridFoldersFactory = <
  T1,
  F1 extends FiltersMap,
  T2,
  F2 extends FiltersMap,
>(
  config: GridFoldersConfig<T1, F1, T2, F2>,
) => GridFoldersState<T1, F1, T2, F2>;

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

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

export function useGridFolders<
  T1,
  F1 extends FiltersMap,
  T2,
  F2 extends FiltersMap,
>(config: GridFoldersConfig<T1, F1, T2, F2>) {
  const createGridFolders = useCreateGridFolders();

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

  return state;
}
