import { useCallback, useEffect, useState } from 'react';
import {
  CollectionConfigWithConditionals,
  useWixPatternsContainer,
  usePrivateCreateCollection,
} from '@wix/bex-core/react';
import { FiltersMap } from '@wix/bex-core';
import { PickerContentState } from '../../state';
import { UsePickerContentParams } from './usePickerContent';

export function useCreatePickerContentState() {
  const { createBILogger } = useWixPatternsContainer();
  const createCollection = usePrivateCreateCollection();

  return useCallback(
    <T, F extends FiltersMap>(params: UsePickerContentParams<T, F>) => {
      const { events, initialSelect, modalState, ...collectionConfig } = params;

      const collection = createCollection(
        {
          ...collectionConfig,
          queryName: modalState.queryName,
          paginationMode: modalState.paginationMode,
          useNewSelectAllLogic: true,
          fetchData: modalState.fetchData as CollectionConfigWithConditionals<
            T,
            F
          >['fetchData'],
          limit: modalState.limit,
          events: {
            ...modalState.events,
            ...events,
          },
        } as CollectionConfigWithConditionals<T, F>,
        {
          paginationModeRef: modalState._paginationModeRef,
        },
      );

      return new PickerContentState({
        modalState,
        collection,
        createBILogger,
        events,
        initialSelect,
      });
    },
    [],
  );
}

export function usePickerContentState<T, F extends FiltersMap>(
  params: UsePickerContentParams<T, F>,
) {
  const createPickerContentState = useCreatePickerContentState();

  const [state] = useState(() => createPickerContentState(params));

  useEffect(() => {
    state.initialSelect = params.initialSelect;
  }, [params.initialSelect]);

  return state;
}
