import {
  WixPatternsContainerOverridesProvider,
  WixPatternsInitialPropsProvider,
  useWixPatternsContainer,
} from '@wix/bex-core/react';
import { CairoProvider } from '../../providers';
import React, { ReactNode, useState } from 'react';
import {
  WixPatternsContainerParams,
  WixPatternsInitialProps,
  FiltersMap,
} from '@wix/bex-core';
import { PickerModalState } from '../../hooks';

export interface PickerContentProviderProps<T, F extends FiltersMap> {
  modalState: PickerModalState<T, F>;
  children?: ReactNode;
}

export function PickerContentProvider<T, F extends FiltersMap>(
  props: PickerContentProviderProps<T, F>,
) {
  const {
    children,
    modalState: { fetchInitialProps },
  } = props;
  const container = useWixPatternsContainer();

  const [initialProps] = useState<WixPatternsInitialProps>(() => ({
    messages: fetchInitialProps.status.value.data?.cairoMessages,
  }));

  // avoid showing toasts under modal context
  // https://wix.slack.com/archives/C4MVDTET1/p1633861135370100
  const [wixPatternsContainerOverrides] = useState<
    Partial<WixPatternsContainerParams>
  >(() => ({
    showToast: () => ({ remove: () => {} }),
    events: container.events,
    onNavigationModal: container.onNavigationModal,
  }));

  return (
    <WixPatternsInitialPropsProvider value={initialProps}>
      <WixPatternsContainerOverridesProvider
        value={wixPatternsContainerOverrides}
      >
        <CairoProvider value={container}>{children}</CairoProvider>
      </WixPatternsContainerOverridesProvider>
    </WixPatternsInitialPropsProvider>
  );
}
