import {
  ArchiveFieldModalState,
  CustomFieldModalState,
  CustomFieldOrigin,
  DataExtensionState,
  ReportBI,
} from '@wix/bex-core';
import { makeAutoObservable } from 'mobx';

export interface CustomFieldsPanelStateParams {
  readonly reportBi: ReportBI;
  readonly closeSidePanel: () => unknown;
  readonly dataExtension: DataExtensionState;
}

export class CustomFieldsPanelState {
  readonly reportBi;
  readonly closeSidePanel;
  readonly dataExtension;
  readonly customFieldModal;
  readonly archiveFieldModal;

  constructor(params: CustomFieldsPanelStateParams) {
    this.reportBi = params.reportBi;
    this.closeSidePanel = params.closeSidePanel;
    this.dataExtension = params.dataExtension;
    this.archiveFieldModal = new ArchiveFieldModalState({
      reportBi: this.reportBi,
      dataExtension: this.dataExtension,
    });
    this.customFieldModal = new CustomFieldModalState({
      reportBi: this.reportBi,
      dataExtensionState: this.dataExtension,
    });
    makeAutoObservable(this);
  }

  openCustomFieldModal(params: {
    fieldId?: string;
    origin: CustomFieldOrigin;
    customOrigin?: string;
  }) {
    const { customFieldModal } = this;

    const { customFieldModalBiReporter } = customFieldModal;

    customFieldModal.reset();
    customFieldModal.mode = params.fieldId ? 'edit' : 'new';
    customFieldModal.origin = params.origin;
    customFieldModal.customOrigin = params.customOrigin;

    !params.fieldId &&
      customFieldModalBiReporter.reportAddCustomField({
        origin: params.origin,
        customOrigin: params.customOrigin,
      });

    customFieldModalBiReporter.formSnapshot = null;
    customFieldModal.setDefaultPermissions();

    if (this.dataExtension.userSchema) {
      if (params.fieldId) {
        const formValues = this.dataExtension.extractFieldValuesFromSchema(
          params.fieldId,
        );

        if (!formValues) {
          return;
        }

        customFieldModal.setFormValues(formValues, {
          disablePermissionCheckboxes: true,
        });
        customFieldModalBiReporter.formSnapshot = formValues;
      }
    }

    customFieldModal.modalState.modal.open();
  }
}
