import React from 'react';
import { observer } from 'mobx-react-lite';
import { usePageContext } from '@wix/bex-core/react';
import { CustomFieldsWidgetState } from '../../state';
import { DeleteFieldModal } from '../ArchivedItemsPanel/DeleteFieldModal';

interface CustomFieldsWidgetCommonComponentsProps {
  state: CustomFieldsWidgetState;
}

const _CustomFieldsWidgetCommonComponents = ({
  state,
}: CustomFieldsWidgetCommonComponentsProps) => {
  const page = usePageContext();

  const { modalsContainerRef, stackingRootRef } = page;

  if (state.isLoading) {
    return null;
  }
  const WixPatternsModalsContainer = state.WixPatternsModalsContainer;
  const CustomFieldModal = state.CustomFieldModal;
  const ArchiveFieldModal = state.ArchiveFieldModal;

  return (
    <>
      {WixPatternsModalsContainer && (
        <WixPatternsModalsContainer
          rootRef={stackingRootRef}
          anchorRef={modalsContainerRef}
          state={state.panels}
        />
      )}
      {CustomFieldModal && (
        <CustomFieldModal state={state.customFieldsPanel.customFieldModal} />
      )}
      {ArchiveFieldModal && (
        <ArchiveFieldModal state={state.customFieldsPanel.archiveFieldModal} />
      )}
      {state.dataExtension.deleteFieldModal && (
        <DeleteFieldModal state={state.dataExtension.deleteFieldModal} />
      )}
    </>
  );
};

export const CustomFieldsWidgetCommonComponents = observer(
  _CustomFieldsWidgetCommonComponents,
);
