import { observer } from 'mobx-react-lite';
import {
  CustomFieldsAllNamespacesFormState,
  CustomFieldsWidgetState,
} from '../../state';
import React, { useState } from 'react';
import { Box } from '@wix/design-system';
import { CustomFieldsNamespaceSectionForm } from './CustomFieldsNamespaceSectionForm';
import { CustomFieldsNamespaceForm } from './CustomFieldsNamespaceForm';
import { OnCustomFieldChange } from './OnCustomFieldChange';
import { EmptyStateContent } from './EmptyStateContent';
import { CustomFieldsEmptyStateOverrides } from './CustomFieldsEmptyStateOverrides';

export interface CustomFieldsAllNamespacesFormProps {
  state: CustomFieldsWidgetState;
  onChange?: OnCustomFieldChange;
  emptyStateOverrides?: CustomFieldsEmptyStateOverrides;
}

function _CustomFieldsAllNamespacesForm(
  props: CustomFieldsAllNamespacesFormProps,
) {
  const {
    state: customFieldsWidgetState,
    onChange,
    emptyStateOverrides,
  } = props;
  const { _userFieldsNamespace } = customFieldsWidgetState;
  const [state] = useState(
    () =>
      (customFieldsWidgetState._formState ??=
        new CustomFieldsAllNamespacesFormState({
          customFieldsWidgetState,
        })),
  );

  const { schemasSections, tpaFieldsExist } = state;

  if (!schemasSections.length) {
    return (
      <EmptyStateContent
        state={customFieldsWidgetState}
        emptyStateOverrides={emptyStateOverrides}
      />
    );
  }

  let child;

  if (tpaFieldsExist) {
    child = (
      <>
        {schemasSections.map((schema, index) => (
          <CustomFieldsNamespaceSectionForm
            key={schema.namespace}
            state={state}
            namespace={schema.namespace as string}
            index={index}
            onChange={onChange}
          />
        ))}
      </>
    );
  } else {
    child = (
      <CustomFieldsNamespaceForm
        state={state}
        namespace={_userFieldsNamespace}
        onChange={onChange}
      />
    );
  }

  return (
    <Box
      direction="vertical"
      width="100%"
      gap="SP3"
      dataHook="custom-fields-form"
    >
      {child}
    </Box>
  );
}

export const CustomFieldsAllNamespacesForm = observer(
  _CustomFieldsAllNamespacesForm,
);
