import React, { useEffect } from 'react';
import { observer } from 'mobx-react-lite';
import { CustomFieldsAllNamespacesFormState } from '../../state';
import { CustomFieldsForm } from '../CustomFieldsForm';
import { OnCustomFieldChange } from './OnCustomFieldChange';
import { Box, InfoIcon, SectionHeader, Text } from '@wix/design-system';
import { useCustomFieldsFormState } from './useCustomFieldsFormState';

export interface CustomFieldsNamespaceSectionFormProps {
  namespace: string;
  state: CustomFieldsAllNamespacesFormState;
  onChange?: OnCustomFieldChange;
  index: number;
}

function _CustomFieldsNamespaceSectionForm(
  props: CustomFieldsNamespaceSectionFormProps,
) {
  const { index, state: allNamespacesFormState, onChange, namespace } = props;

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

  const {
    _customFieldsWidgetState: {
      container: { translate: t },
      _userFieldsNamespace,
    },
  } = allNamespacesFormState;

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

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

  return (
    <Box
      key={namespace}
      dataHook={`custom-fields-namespace-form-${namespace}`}
      direction="vertical"
      width="100%"
      gap="SP3"
      paddingTop={index > 0 ? 'SP3' : undefined}
    >
      <SectionHeader
        dataHook="section-header"
        title={<Text secondary>{state.appName}</Text>}
        suffix={
          namespace !== _userFieldsNamespace && (
            <InfoIcon
              dataHook="info-icon"
              content={t('cairo.customFields.tpaSection.tooltip')}
              size="small"
            />
          )
        }
        skin="light"
        divider={index > 0 ? 'top' : 'none'}
        size="medium"
        horizontalPadding="xxTiny"
      />

      <CustomFieldsForm state={state} onChange={onChange} />
    </Box>
  );
}

export const CustomFieldsNamespaceSectionForm = observer(
  _CustomFieldsNamespaceSectionForm,
);
