import { Typography, TypographyTypeMap } from '@mui/material';
import { FC } from 'react';
import { useTranslation } from 'react-i18next';
import { ERRORS } from './Errors';

interface Props {
  //eslint-disable-next-line @typescript-eslint/no-explicit-any
  error: any;
  context?: string;
  color?: TypographyTypeMap['props']['color'];
}

const ErrorComponent: FC<Props> = ({ error, context, color = 'error.main' }) => {
  const { t } = useTranslation();

  if (!error) return null;

  if (error.code) {
    switch (error.code) {
      case ERRORS.NOT_FOUND:
        return <Typography color={color}>{t(error.code, { context: `${error.entity}:${context}` })}</Typography>;
      case ERRORS.NOT_ALLOWED:
      case ERRORS.UNAUTHORIZED:
        console.log(error, context);
        return <Typography color={color}>{t(error.code, { context })}</Typography>;
      case ERRORS.FAILED_UPDATE:
        return error.fields.map((field: string, index: number) => (
          <Typography key={`error_${field}`} color={color}>
            {t(error.code, { context: `${error.reasons[index]}:${field}:${context}` })}
          </Typography>
        ));
      case ERRORS.MISSING_FIELD:
        return error.fields.map((field: string) => (
          <Typography key={`error_${field}`} color={color}>
            {t(error.code, { context: `${field}:${context}` })}
          </Typography>
        ));
      case ERRORS.DUPLICATE:
        return <Typography color={color}>{t(error.code, { context: `${error.entity}:${context}` })}</Typography>;
    }
  }

  return <Typography color={color}>{t(error?.message ?? 'Unknown', { context })}</Typography>;
};

export default ErrorComponent;
