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 {
  FlowBusinessManagerModule,
  useComponentInfo,
  useModuleInfo,
  useModuleParams,
} from '@wix/yoshi-flow-bm';
import { useErrorMonitorCompat } from './errorMonitorCompat';
import { getModule } from '@wix/business-manager-api';
import { useCallback, useState } from 'react';

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

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

export type UsePickerModalParams<
  T,
  F extends FiltersMap,
> = UsePickerModalParamsBM<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 moduleParams = useModuleParams();
  const moduleInfo = useModuleInfo();
  const componentInfo = useComponentInfo();
  const errorMonitor = useErrorMonitorCompat();
  const createPicker = useCreatePickerModalBase();

  return useCallback<PikerModalFactory>(
    <T, F extends FiltersMap = OptionalFiltersMap>(
      params: UsePickerModalParams<T, F>,
    ) => {
      const { accountLanguage: language } = moduleParams;
      const { moduleId } = moduleInfo;
      const { componentId } = componentInfo;

      const { _essentials } = getModule(
        moduleId as any,
      ) as FlowBusinessManagerModule;

      return createPicker({
        ...params,
        environment: wixPatternsEnvironment({
          language,
          componentId,
          artifactId: moduleId,
          ...params?.environment,
        }),
        errorMonitor,
        biLoggerFactory: _essentials.biLoggerFactory,
      } 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;
}
