import React from 'react';
import { observer } from 'mobx-react-lite';
import type { CustomFieldsWidgetState } from '../../state';
import { Refresh as RefreshIcon } from '@wix/wix-ui-icons-common';
import { LoadingErrorState } from '../ErrorState';
import { CustomFieldsWidgetContentLazy } from './CustomFieldsWidgetContentLazy';
import { CustomFieldsWidgetProps } from './types';
import { InlineSkeletonContent } from './Skeletons';

interface CustomFieldsWidgetInlineProps {
  state: CustomFieldsWidgetState;
  extendedFields?: CustomFieldsWidgetProps['extendedFields'];
  emptyStateOverrides: CustomFieldsWidgetProps['emptyStateOverrides'];
  onChange?: CustomFieldsWidgetProps['onChange'];
  dataHook: CustomFieldsWidgetProps['dataHook'];
}

const _CustomFieldsWidgetInline = (props: CustomFieldsWidgetInlineProps) => {
  const { state, emptyStateOverrides, onChange, dataHook } = props;
  const { translate: t } = state.dataExtension.container;

  const renderContent = () => {
    if (state.isLoading) {
      return <InlineSkeletonContent />;
    }

    if (state.isError) {
      return (
        <LoadingErrorState
          dataHook="custom-fields-widget-inline-error"
          title={t('cairo.customFields.technical.error.title')}
          action={{
            prefixIcon: <RefreshIcon />,
            text: t('cairo.toast.retry'),
            onClick: state.retry,
          }}
        />
      );
    }

    return (
      <CustomFieldsWidgetContentLazy
        emptyStateOverrides={emptyStateOverrides}
        onChange={onChange}
      />
    );
  };

  return <div data-hook={dataHook}>{renderContent()}</div>;
};

export const CustomFieldsWidgetInline = observer(_CustomFieldsWidgetInline);
