import {
  Box,
  CustomModalLayoutProps,
  TextButton,
  Text,
} from '@wix/design-system';
import {
  ExportState,
  FiltersMap,
  isWixPatternsError,
  WixPatternsError,
} from '@wix/bex-core';
import React, { ReactElement } from 'react';
import { isErrorDetailsHttpError, isHttpError } from '@wix/bex-core/util';
import { ApplicationError } from '@wix/bex-utils/@wix/ambassador-fedinfra-exportservice-v1-export-async-job/types';

export type RenderModalError = (
  data: ApplicationError['data'],
) => undefined | Partial<CustomModalLayoutProps & { children?: ReactElement }>;

export function getExportModalErrorProps<T, F extends FiltersMap>({
  renderError,
  state,
}: {
  state: ExportState<T, F>;
  renderError?: RenderModalError;
}): Partial<CustomModalLayoutProps & { children?: ReactElement }> {
  const {
    exportStatus: { error: _error },
    translate: t,
    errorHandler,
  } = state;

  const error = isWixPatternsError(_error)
    ? (_error as WixPatternsError).originalException
    : _error;

  const details = isErrorDetailsHttpError(error) ? error.response.data : null;
  const applicationErrorCode = details?.applicationError?.code;
  const applicationErrorData = details?.applicationError?.data;

  if (!isHttpError(error)) {
    return {};
  }

  if (applicationErrorCode === 'method_endpoint_permission_denied') {
    return {
      children: (
        <Box direction="vertical">
          <Text widows>{t('cairo.export.noPermissionsMessage')}</Text>
          <TextButton
            dataHook="export-error-message-action"
            as="a"
            href="https://support.wix.com/en/article/roles-permissions-overview"
            target="_blank"
          >
            {t('cairo.export.noPermissionsCTA')}
          </TextButton>
        </Box>
      ),
    };
  }

  if (
    applicationErrorCode === 'media_generate_signed_url' ||
    applicationErrorCode === 'media_appender_completion' ||
    applicationErrorCode === 'async_job_infra'
  ) {
    return {
      children: (
        <Box direction="vertical">
          <Text widows>{t('cairo.export.databaseIssueMessage')}</Text>
          <TextButton
            dataHook="export-error-message-action"
            as="a"
            href="https://www.wix.com/contact"
            target="_blank"
          >
            {t('cairo.error.contactSupport.cta')}
          </TextButton>
        </Box>
      ),
    };
  }

  if (applicationErrorCode === 'max_polling_stale_job') {
    return {
      children: (
        <Box direction="vertical">
          <Text widows>{t('cairo.export.overloadErrorMessage')}</Text>
          <TextButton
            dataHook="export-error-message-action"
            as="a"
            onClick={state.onRetryExportToClick}
          >
            {t('cairo.export.tryAgain')}
          </TextButton>
        </Box>
      ),
    };
  }

  if (applicationErrorCode === 'offline') {
    return {
      title: t('cairo.connection.error.title'),
      children: <Text widows>{t('cairo.export.offlineMessage')}</Text>,
    };
  }

  if (applicationErrorCode === 'grpc_query_target_internal') {
    return {
      children: (
        <Box direction="vertical">
          <Text widows>{t('cairo.export.serverErrorMessage')}</Text>
          <TextButton
            dataHook="export-error-message-action"
            as="a"
            href="https://www.wix.com/contact"
            target="_blank"
          >
            {t('cairo.error.contactSupport.cta')}
          </TextButton>
        </Box>
      ),
      ...renderError?.(applicationErrorData),
    };
  }

  const resolvedError = errorHandler.getResolvedError?.(error);

  return {
    children: (
      <Box direction="vertical">
        <Text widows>{resolvedError?.message}</Text>
        {resolvedError?.action && (
          <TextButton
            dataHook="export-error-message-action"
            as="a"
            onClick={resolvedError?.action?.onClick}
          >
            {resolvedError?.action?.text}
          </TextButton>
        )}
      </Box>
    ),
  };
}
