import React, { useEffect, useState } from 'react';
import { observer } from 'mobx-react-lite';
import { reaction } from 'mobx';
import { CustomFieldModalState, type ImportState } from '@wix/bex-core';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import { CustomFieldModal } from '../CustomFieldModal';
import { mappingToFieldDraft } from './dataExtensionFieldDraft';

/**
 * The DataExtension create/edit-field modal for the import flow. `ImportButton`
 * picks and lazy-loads it for a platformized import (from the config's
 * `dataSource`). Reuses `CustomFieldModal` in side-effect-free mode (`onSubmit`)
 * — on confirm it hands the draft to the import (which batches creation
 * pre-upload) instead of creating the field. It opens/pre-fills from
 * `state.editingMapping` and clears `state.editingHeader` on close, mirroring the
 * CMS editor.
 */
const _DataExtensionImportFieldEditor = ({ state }: { state: ImportState }) => {
  const container = useWixPatternsContainer();
  const fieldManagement = state.dataExtensionFieldManagement;

  const [editorState] = useState(() =>
    fieldManagement
      ? new CustomFieldModalState({
          fieldManagement,
          container,
          reportBi: container.reportBi,
          fieldCount: () => state.fields.length,
          onSubmit: state.applyDataExtensionFieldEdit,
        })
      : undefined,
  );

  useEffect(() => {
    if (!editorState || !fieldManagement) {
      return undefined;
    }
    const disposeOpen = reaction(
      () => state.editingMapping,
      (mapping) => {
        const header = state.editingHeader;
        if (mapping && header && !editorState.modalState.isOpen) {
          const name = mapping.displayName ?? header;
          editorState.reset();
          editorState.mode = 'new';
          editorState.setFormValues(
            mappingToFieldDraft(
              mapping,
              editorState.generateUniqueKey(name),
              name,
              fieldManagement,
            ),
          );
          editorState.modalState.modal.open();
        }
      },
      { fireImmediately: true },
    );
    const disposeClose = reaction(
      () => editorState.modalState.isOpen,
      (isOpen) => {
        if (!isOpen && state.editingHeader != null) {
          state.endFieldEdit();
        }
      },
    );
    return () => {
      disposeOpen();
      disposeClose();
    };
  }, []);

  if (!editorState) {
    return null;
  }

  return <CustomFieldModal state={editorState} />;
};

export const DataExtensionImportFieldEditor = observer(
  _DataExtensionImportFieldEditor,
);
