import React, { ReactElement } from 'react';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import { OfflineErrorState } from './OfflineErrorState';
import { CollectionErrorState } from '../CollectionErrorState';
import { observer } from 'mobx-react-lite';
import { isServerErrorCode } from '@wix/bex-core';

export interface ErrorStateProps {
  dataHook?: string;
  errorStatus?: {
    error: unknown;
  } | null;
  /** @deprecated */
  renderError?: (params: {
    err: unknown;
    isOnline: boolean;
    retry: () => void;
  }) => ReactElement;
  errorState?: (
    err: unknown,
    params: {
      isOnline: boolean;
      retry: () => void;
    },
  ) => ReactElement;
  state: {
    errorStatus?: {
      error: unknown;
    } | null;
    retryErrorState: () => void;
  };
  image?: ReactElement;
}

function _ErrorState({
  state,
  errorStatus: errorStatusProp,
  errorState,
  dataHook,
  image,
}: ErrorStateProps) {
  const {
    onlineState: { isOnline },
    errorHandler,
    translate: t,
  } = useWixPatternsContainer();

  const errorStatus = errorStatusProp ?? state.errorStatus;

  if (!isOnline) {
    return (
      <OfflineErrorState
        image={image}
        onRetry={state.retryErrorState}
        dataHook={dataHook}
      />
    );
  }

  if (errorState && errorStatus) {
    return errorState(errorStatus.error, {
      isOnline,
      retry: state.retryErrorState,
    });
  }

  const resolvedError = errorHandler.getResolvedError?.(errorStatus?.error);
  const action =
    resolvedError?.action ??
    (isServerErrorCode(errorStatus?.error)
      ? { text: t('cairo.error.tryAgain.cta'), onClick: state.retryErrorState }
      : undefined);

  return (
    <CollectionErrorState
      dataHook={dataHook}
      title={t('cairo.technical.error.title', {
        defaultValue: 'We couldn’t load your items',
      })}
      subtitle={resolvedError?.message}
      action={
        action && { text: action?.text, onClick: () => action?.onClick?.() }
      }
      requestId={resolvedError?.requestId}
    />
  );
}

export const ErrorState = observer(_ErrorState);
