import { CustomFieldsViewWidgetState, ExtendedFields } from '@wix/bex-core';
import { Box, Divider } from '@wix/design-system';
import React from 'react';
import { CustomFieldsViewWidgetSection } from './CustomFieldsViewWidgetSection';
import { observer } from 'mobx-react-lite';
import { useWixPatternsContainer } from '@wix/bex-core/react';

interface CustomFieldsViewWidgetContentProps {
  state: CustomFieldsViewWidgetState;
  extendedFields?: ExtendedFields;
  userFieldsTitle?: string;
}

const _CustomFieldsViewWidgetContent = ({
  state,
  extendedFields,
  userFieldsTitle,
}: CustomFieldsViewWidgetContentProps) => {
  const { translate: t } = useWixPatternsContainer();
  const getSections = () => {
    return state.dataExtension.allNamespaces
      .map((namespace) => {
        const relevantCustomFields =
          state.getExtendedFieldsToDisplayForNamespace(
            namespace,
            extendedFields,
          );
        if (relevantCustomFields.length === 0) {
          return null;
        }

        const title =
          namespace === state.userFieldsNamespace
            ? userFieldsTitle || t('cairo.customFields.entityPage.sectionTitle')
            : state.getAppName(namespace);

        return (
          <Box marginBottom="SP1">
            <CustomFieldsViewWidgetSection
              title={title}
              customFields={relevantCustomFields}
              namespace={namespace}
              fieldValues={
                extendedFields?.namespaces?.[
                  namespace as keyof typeof extendedFields.namespaces
                ] || {}
              }
            />
          </Box>
        );
      })
      .filter(Boolean) as JSX.Element[];
  };

  const sectionsWithDividers = (sections: JSX.Element[]) => {
    return sections.map((section, index) => (
      <React.Fragment key={index}>
        {section}
        {index < sections.length - 1 && (
          <Box marginTop="SP4" marginBottom="SP4">
            <Divider />
          </Box>
        )}
      </React.Fragment>
    ));
  };
  const renderCustomFields = () => {
    const sections = getSections();
    return sectionsWithDividers(sections);
  };

  return (
    <Box direction="vertical" dataHook="fields-content">
      {renderCustomFields()}
    </Box>
  );
};

export const CustomFieldsViewWidgetContent = observer(
  _CustomFieldsViewWidgetContent,
);
