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

interface CustomFieldsWidgetCommonComponentsProps {
  state: CustomFieldsWidgetState;
}

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

  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={
            useRelativeSidePanel ? stackingRootRef : modalsContainerRef
          }
          state={state.panels}
        />
      )}
      {CustomFieldModal && (
        <CustomFieldModal state={state.customFieldsPanel.customFieldModal} />
      )}
      {ArchiveFieldModal && state.customFieldsPanel.archiveFieldModal && (
        <ArchiveFieldModal state={state.customFieldsPanel.archiveFieldModal} />
      )}
      <DeleteFieldModal state={state.customFieldsPanel.deleteFieldModal} />
    </>
  );
};

export const CustomFieldsWidgetCommonComponents = observer(
  _CustomFieldsWidgetCommonComponents,
);
