import type { FC } from 'react';
import type { TextProps } from '../Text';

import prettyWrap from '~/src/lib/utils/prettyWrap';
import Text from '../Text';

type ToTextParams = {
  error: { message: string };
  status?: number;
};

type ErrorType = { message: string; status?: number };

export interface ErrorTextProps extends Omit<TextProps, 'children'> {
  error?: ErrorType;
  toText?: (params: ToTextParams) => string | undefined;
}

const ErrorText: FC<ErrorTextProps> = ({
  error,
  toText: toTextCustom,

  ...props
}) => {
  if (!error) return null;

  const toTextParams = resolveToErrorTextParams(error);
  const customText = toTextCustom && toTextCustom(toTextParams);

  return (
    <Text isParagraph {...props}>
      {prettyWrap(customText || toDefaultErrorText(toTextParams))}
    </Text>
  );
};

export const resolveToErrorTextParams = (error: ErrorType): ToTextParams => {
  return { error, status: error.status };
};

export const toDefaultErrorText = ({ error, status }: ToTextParams) => {
  if (status) {
    switch (status) {
      case 0:
        return 'Unable to fetch data, you may be offline';
      case 404:
        return "We couldn't find that";
      case 401:
        return 'Session expired';
      case 403:
        return 'Access denied';
      case 500:
        return 'The server encountered a problem';
      default:
        return error.message || `${status} error`;
    }
  }

  return error.message;
};

export default ErrorText;
