import { FiltersMap, OptionalFiltersMap } from '@wix/bex-core';
import {
  useWixPatternsContainer,
  CollectionConfigWithConditionals,
  useCreateCollection,
} from '@wix/bex-core/react';
import { GridState } from '../state';
import { useOptionalCachedState } from './useOptionalCachedState';

export type GridCollection = <T, F extends FiltersMap = OptionalFiltersMap>(
  config: CollectionConfigWithConditionals<T, F>,
) => GridState<T, F>;

export const useGridCollection: GridCollection = <
  T,
  F extends FiltersMap = OptionalFiltersMap,
>(
  config: CollectionConfigWithConditionals<T, F>,
): GridState<T, F> => {
  const container = useWixPatternsContainer();
  const createCollection = useCreateCollection();

  const state = useOptionalCachedState(
    () =>
      new GridState<T, F>({
        collection: createCollection<T, F>(config),
        container,
      }),
  );

  return state;
};
