import {
  useCreatePickerModal as useCreatePickerModalBase,
  UsePickerModalParamsBase,
  UsePickerModalParams as UsePickerModalParamsOriginal,
  PickerModalState,
  useSyncPickerModalProps,
} from '../hooks';
import {
  wixPatternsEnvironment,
  FiltersMap,
  OptionalFiltersMap,
} from '@wix/bex-core';
import { PaginationModeConfig } from '@wix/bex-core/react';
import { useEssentials } from '@wix/fe-essentials/react';
import { useCallback, useState } from 'react';

interface UsePickerModalParamsOverrides<T, F extends FiltersMap> {
  environment?: Partial<UsePickerModalParamsBase<T, F>['environment']>;
}

type UsePickerModalParamsEssentials<T, F extends FiltersMap> = Omit<
  UsePickerModalParamsBase<T, F>,
  | 'paginationMode'
  | 'fetchData'
  | 'environment'
  | 'errorMonitor'
  | 'biLoggerFactory'
>;

export type UsePickerModalParams<
  T,
  F extends FiltersMap,
> = UsePickerModalParamsEssentials<T, F> &
  UsePickerModalParamsOverrides<T, F> &
  PaginationModeConfig<T, F>;

export type PikerModalFactory = <T, F extends FiltersMap = OptionalFiltersMap>(
  config: UsePickerModalParams<T, F>,
) => PickerModalState<T, F>;

export function useCreatePickerModal(): PikerModalFactory {
  const { errorMonitor, environment, biLoggerFactory } = useEssentials();
  const createPickerModalBase = useCreatePickerModalBase();

  return useCallback<PikerModalFactory>(
    <T, F extends FiltersMap = OptionalFiltersMap>(params: any) =>
      createPickerModalBase({
        errorMonitor,
        biLoggerFactory,
        ...params,
        environment: wixPatternsEnvironment({
          ...environment,
          ...params?.environment,
        }),
      } as UsePickerModalParamsOriginal<T, F>),
    [],
  );
}

export function usePickerModal<T, F extends FiltersMap = OptionalFiltersMap>(
  params: UsePickerModalParams<T, F>,
) {
  const createPickerModal = useCreatePickerModal();
  const [state] = useState(() => createPickerModal<T, F>(params));
  useSyncPickerModalProps(state, params);
  return state;
}
