import { useCallback, useState } from 'react';
import { FiltersMap } from '@wix/bex-core';
import { ViewsState } from '../state';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import { View } from '../model';
import { CollectionViewsDropdownProps } from '../components/CollectionViewsDropdown';
import { presetsToCategories } from '../state/presetsToCategories';

export interface ViewsConfig<F extends FiltersMap> {
  namespace: string;
  presets?: CollectionViewsDropdownProps<F>['presets'];
  allItemsViewProps?: CollectionViewsDropdownProps<F>['allItemsViewProps'];
  initialSelect?: true | ((item: View<F>, index: number) => boolean);
  fqdn: string;
}

export type ViewsFactory = <F extends FiltersMap>(
  config: ViewsConfig<F>,
) => ViewsState<F>;

export function useCreateViews(): ViewsFactory {
  const container = useWixPatternsContainer();

  return useCallback<ViewsFactory>(
    <F extends FiltersMap>(config: ViewsConfig<F>) => {
      const { namespace, presets, initialSelect, fqdn, allItemsViewProps } =
        config;

      return new ViewsState({
        oldNamespace: namespace,
        presets: presetsToCategories(presets),
        container,
        initialSelect,
        fqdn,
        allItemsViewProps,
        reportBI: () => {},
      });
    },
    [],
  );
}

export const useViews: ViewsFactory = (config) => {
  const createViews = useCreateViews();

  const [state] = useState(() => createViews(config));

  return state;
};
