import React, { useEffect } from 'react';
import { observer } from 'mobx-react-lite';
import { CustomFieldsAllNamespacesFormState } from '../../state';
import { CustomFieldsForm } from '../CustomFieldsForm';
import { OnCustomFieldChange } from './OnCustomFieldChange';
import { useCustomFieldsFormState } from './useCustomFieldsFormState';

export interface CustomFieldsNamespaceFormProps {
  namespace: string;
  state: CustomFieldsAllNamespacesFormState;
  onChange?: OnCustomFieldChange;
}

function _CustomFieldsNamespaceForm(props: CustomFieldsNamespaceFormProps) {
  const { state: allNamespacesFormState, onChange, namespace } = props;

  const state = useCustomFieldsFormState({
    state: allNamespacesFormState,
    namespace,
  });

  useEffect(() => state.init(), []);

  if (!state.writeableFields.length) {
    return null;
  }

  return <CustomFieldsForm state={state} onChange={onChange} />;
}

export const CustomFieldsNamespaceForm = observer(_CustomFieldsNamespaceForm);
