import { FiltersMap, OptionalFiltersMap } from '@wix/bex-core';
import {
  useWixPatternsContainer,
  useWixPatternsContainerOverrides,
  CollectionConfigWithConditionals,
  useCreateCollection,
  useCreateOptimisticActions,
} from '@wix/bex-core/react';
import {
  LayoutSwitchState,
  LayoutSwitchStateParams,
  SpreadsheetLayoutConfig,
  TableLayoutConfig,
  GridLayoutConfig,
} from '../state/LayoutSwitchState';
import { useOptionalCachedState } from './useOptionalCachedState';

export type LayoutSwitchCollectionConfig<
  T,
  F extends FiltersMap,
> = CollectionConfigWithConditionals<T, F> & {
  table?: TableLayoutConfig;
  grid?: GridLayoutConfig;
  spreadsheet?: Omit<SpreadsheetLayoutConfig<T, F>, 'createOptimisticActions'>;
};

export const useLayoutSwitchCollection = <
  T,
  F extends FiltersMap = OptionalFiltersMap,
>(
  config: LayoutSwitchCollectionConfig<T, F>,
): LayoutSwitchState<T, F> => {
  const container = useWixPatternsContainer();
  const containerOverrides = useWixPatternsContainerOverrides();
  const createCollection = useCreateCollection();
  const createOptimisticActions = useCreateOptimisticActions();

  const state = useOptionalCachedState(() => {
    const collection = createCollection<T, F>(config);

    const spreadsheet: LayoutSwitchStateParams<T, F>['spreadsheet'] =
      config.spreadsheet
        ? {
            ...config.spreadsheet,
            createOptimisticActions: (c) => createOptimisticActions(c),
          }
        : undefined;

    return new LayoutSwitchState<T, F>({
      collection,
      container,
      containerOverrides,
      table: config.table,
      grid: config.grid,
      spreadsheet,
    });
  });

  return state;
};
