import { useCallback, useEffect, useState } from 'react';
import type { FiltersMap, OptionalFiltersMap } from '@wix/bex-core';
import { CursorFetchDataFn, OffsetFetchDataFn } from '@wix/bex-core/react';
import { UsePickerModalParamsBase } from './UsePickerModalParamsBase';
import { PickerModalState } from './PickerModalState';
import { configure } from '@wix/bex-utils/react-dom';
import { version as cairoVersion } from '../../version';

configure();

type PaginationModeConfig<T, F extends FiltersMap> =
  | {
      paginationMode?: 'offset';
      fetchData: OffsetFetchDataFn<T, F>;
    }
  | {
      paginationMode: 'cursor';
      fetchData: CursorFetchDataFn<T, F>;
    };

export type UsePickerModalParams<T, F extends FiltersMap> = Omit<
  UsePickerModalParamsBase<T, F>,
  'paginationMode' | 'fetchData'
> &
  PaginationModeConfig<T, F>;

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

export function useCreatePickerModalState(): PikerModalFactory {
  return useCallback<PikerModalFactory>(
    <T, F extends FiltersMap = OptionalFiltersMap>(
      params: UsePickerModalParams<T, F>,
    ) =>
      new PickerModalState({
        ...params,
        environment: {
          ...params.environment,
          uiLibVersion: cairoVersion,
        },
      }),
    [],
  );
}

export function useSyncPickerModalProps<
  T,
  F extends FiltersMap = OptionalFiltersMap,
>(
  state: PickerModalState<T, F> | null,
  {
    onSelect,
    disableAutoSelectOnSingleItem,
  }: Pick<
    UsePickerModalParams<T, F>,
    'onSelect' | 'disableAutoSelectOnSingleItem'
  >,
) {
  useEffect(() => {
    if (!state) {
      return;
    }
    state.onSelectRef.current = onSelect;
  }, [onSelect]);

  useState(() => {
    if (!state) {
      return;
    }
    if (state.isModalOpen) {
      state.prefetch();
    }
    state.disableAutoSelectionRef.current = disableAutoSelectOnSingleItem;
  });

  useEffect(() => {
    if (!state) {
      return;
    }
    state.disableAutoSelectionRef.current = disableAutoSelectOnSingleItem;
  }, [disableAutoSelectOnSingleItem]);
}

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