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

type TableCollectionConfig<
  T,
  F extends FiltersMap,
> = CollectionConfigWithConditionals<T, F> & {
  aiAssistant?: AiAssistant;
};

type TableCollection = <T, F extends FiltersMap = OptionalFiltersMap>(
  config: TableCollectionConfig<T, F>,
) => TableState<T, F>;

export const useTableCollection: TableCollection = <
  T,
  F extends FiltersMap = OptionalFiltersMap,
>(
  config: TableCollectionConfig<T, F>,
): TableState<T, F> => {
  const container = useWixPatternsContainer();
  const createCollection = useCreateCollection();

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

  config.aiAssistant?.useAiAssistant({
    collection: state.collection,
    loadingRowState: state.loadingRowState,
  });
  return state;
};
