import React, { useEffect, useState } from 'react';
import { observer } from 'mobx-react-lite';
import { reaction } from 'mobx';
import type { ImportState } from '@wix/bex-core';
import { FieldEditorModal } from '../CmsFieldManagement/FieldEditorModal';
import { FieldEditorModalState } from '../CmsFieldManagement/FieldEditorModalState';
import { buildFieldDraft } from './importFieldEditor';

/**
 * The CMS create/edit-field modal for the import flow. `ImportButton` picks and
 * lazy-loads it for a CMS (Wix Data) import (from the config's `dataSource`).
 * Self-contained: it opens and pre-fills from `state.editingMapping` when a
 * column starts editing, writes the result back via `state.applyFieldEdit`, and
 * clears `state.editingHeader` on close so re-editing the same column re-opens it.
 */
const _CmsImportFieldEditor = ({ state }: { state: ImportState }) => {
  const t = state.translate;
  const [editorState] = useState(
    () => new FieldEditorModalState({ onSubmit: state.applyFieldEdit }),
  );

  useEffect(() => {
    const disposeOpen = reaction(
      () => state.editingMapping,
      (mapping) => {
        const header = state.editingHeader;
        if (mapping && header && !editorState.modal.isOpen) {
          editorState.open(buildFieldDraft(header, mapping));
        }
      },
      { fireImmediately: true },
    );
    const disposeClose = reaction(
      () => editorState.modal.isOpen,
      (isOpen) => {
        if (!isOpen && state.editingHeader != null) {
          state.endFieldEdit();
        }
      },
    );
    return () => {
      disposeOpen();
      disposeClose();
    };
  }, []);

  return (
    <FieldEditorModal
      state={editorState}
      title={t('cairo.import.editField')}
      primaryButtonText={t('cairo.import.save')}
      secondaryButtonText={t('cairo.import.cancel')}
      // The mapping dropdown's popover renders at z-index 5001. Opening the editor
      // from the "+ Create New Field" footer doesn't synchronously close that
      // popover, so the editor must stack above it — below the field-type dropdown
      // inside the editor (10000) and toasts (5500).
      zIndex={5100}
    />
  );
};

export const CmsImportFieldEditor = observer(_CmsImportFieldEditor);
