import { ExtendedFields } from '@wix/bex-core';
import { observer } from 'mobx-react-lite';
import React from 'react';
import { Box, Card, Heading } from '@wix/design-system';
import { CustomFieldsViewWidgetContent } from './CustomFieldsViewWidgetContent';
import { useCustomFieldsViewWidget } from './useCustomFieldsViewWidget';
import { CustomFieldsViewWidgetInline } from './CustomFieldsViewWidgetInline';
import { CardContainer } from '../CardContainer';
import { useWidgetPageStatus } from '../useWidgetPageStatus';
import { EmptyStateViewContent } from './EmptyStateViewContent';

export interface CustomFieldsViewWidgetProps {
  /**
   * Applies a data-hook HTML attribute that can be used in tests.
   */
  dataHook?: string;

  /**
   * The FQDN used to fetch the schema from the data-extension service.
   */
  fqdn: string;

  extensionPoint?: string;

  /**
   * The current values of the extended fields. Typically, these values are found
   * under the `extendedFields` property of the related entity (e.g., `myEntity.extendedFields`).
   */
  extendedFields?: ExtendedFields;

  /**
   * A custom title for the widget. Overrides the default title.
   */
  title?: string;

  /**
   * A custom title for the "user-defined fields" section. Overrides the default section title.
   */
  userFieldsTitle?: string;

  /**
   * Determines the visual style of the widget.
   * - `'inline'`: The widget is rendered inline with the surrounding content.
   * - `'card'`: The widget is displayed in a card container.
   */
  theme?: 'inline' | 'card';
}

const _CustomFieldsViewWidget = ({
  dataHook,
  fqdn,
  extendedFields,
  title,
  userFieldsTitle,
  extensionPoint,
  theme = 'card',
}: CustomFieldsViewWidgetProps) => {
  const customFieldsViewWidget = useCustomFieldsViewWidget({
    fqdn,
    extendedFields,
    extensionPoint,
    theme,
  });

  const {
    state,
    userCustomFields,
    appsCustomFields,
    container,
    areAllCustomFieldsEmpty,
  } = customFieldsViewWidget;

  const { translate: t } = container;

  const { status } = useWidgetPageStatus(state.initTask.status.status);

  if (
    !state.isLoading &&
    !state.isError &&
    !userCustomFields.length &&
    !appsCustomFields.length
  ) {
    return null;
  }

  if (theme === 'inline') {
    return (
      <CustomFieldsViewWidgetInline
        dataHook={dataHook}
        extendedFields={extendedFields}
        userFieldsTitle={userFieldsTitle}
        {...customFieldsViewWidget}
      />
    );
  }

  return (
    <CardContainer
      stretchVertically
      dataHook={dataHook}
      status={status}
      errorState={{
        dataHook: 'error-state',
        action: {
          text: t('cairo.entityPage.widgetError.TPAconnectionFail.CTA'),
          onClick: () => state.retry(),
        },
      }}
    >
      <Card.Header
        dataHook="custom-fields-view-widget-header"
        title={
          <HeaderTitle
            title={title ?? t('cairo.customFields.entityPage.title')}
          />
        }
      />
      <Card.Divider />
      <Card.Content dataHook="custom-fields-view-widget-content">
        {areAllCustomFieldsEmpty ? (
          <EmptyStateViewContent
            title={t('cairo.customFields.entityPage.emptyState.title')}
            subtitle={t('cairo.customFields.entityPage.emptyState.subtitle')}
          />
        ) : (
          <CustomFieldsViewWidgetContent
            state={state}
            extendedFields={extendedFields}
            userFieldsTitle={userFieldsTitle}
          />
        )}
      </Card.Content>
    </CardContainer>
  );
};

export const CustomFieldsViewWidget = observer(_CustomFieldsViewWidget);

const HeaderTitle = ({ title }: { title: string }) => {
  return (
    <Box gap="SP1">
      <Heading size="medium">{title}</Heading>
    </Box>
  );
};
