import React from 'react';
import { observer } from 'mobx-react-lite';
import { CustomFieldsWidgetState } from '../../state';
import { CardContainer } from '../CardContainer';
import { Box, Card, InfoIcon } from '@wix/design-system';
import { Heading } from '../Heading';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import { CustomFieldsWidgetContentLazy } from './CustomFieldsWidgetContentLazy';
import { Refresh } from '@wix/wix-ui-icons-common';
import { CustomFieldsWidgetProps } from './types';
import { useWidgetPageStatus } from '../useWidgetPageStatus';

interface CustomFieldsWidgetCardProps {
  state: CustomFieldsWidgetState;
  subtitle?: CustomFieldsWidgetProps['subtitle'];
  dataHook?: CustomFieldsWidgetProps['dataHook'];
  emptyStateOverrides?: CustomFieldsWidgetProps['emptyStateOverrides'];
  onChange?: CustomFieldsWidgetProps['onChange'];
}

const _CustomFieldsWidgetCard = ({
  state,
  subtitle,
  dataHook,
  emptyStateOverrides = {},
  onChange,
}: CustomFieldsWidgetCardProps) => {
  const { status } = useWidgetPageStatus(state.initTask.status.status);
  const container = useWixPatternsContainer();
  const { translate: t } = container;

  const headerSubtitle =
    subtitle || t('cairo.customFields.entityPage.subtitle');
  const headerTitle = (
    <Box gap="SP1">
      <Heading size="medium">
        {t('cairo.customFieldsWidget.entityPage.title')}
      </Heading>
      {state.widgetSize !== 'default' ? (
        <InfoIcon dataHook="subtitle-info-icon" content={headerSubtitle} />
      ) : null}
    </Box>
  );

  const ActionsButton = state.ActionButtonsComponent;
  const suffix = ActionsButton ? <ActionsButton state={state} /> : null;

  return (
    <CardContainer
      stretchVertically
      dataHook={dataHook}
      status={status}
      errorState={{
        dataHook: 'error-state',
        title: t('cairo.customFields.technical.error.title'),
        subtitle: t('cairo.technical.error.text'),
        action: {
          text: t('cairo.error.tryAgain.cta'),
          prefixIcon: <Refresh />,
          onClick: state.retry,
        },
      }}
    >
      <Card.Header
        dataHook="custom-fields-widget-header"
        title={headerTitle}
        subtitle={state.widgetSize === 'default' ? headerSubtitle : null}
        suffix={suffix}
      />
      <Card.Divider />
      <Card.Content dataHook="custom-fields-widget-content">
        <CustomFieldsWidgetContentLazy
          emptyStateOverrides={emptyStateOverrides}
          onChange={onChange}
        />
      </Card.Content>
    </CardContainer>
  );
};

export const CustomFieldsWidgetCard = observer(_CustomFieldsWidgetCard);
