import "./style.pcss";

import type { FC, ReactElement } from "react";
import { useCallback } from "react";
import type { IErrorInfo } from "./config/types";
import { isErrorInstance } from "./utils/isErrorInstance";
import type { IComponentBaseProps } from "../../types/components/index";
import { useCN } from "../../utils/react/useCN";

/**
 * Компонент информации об ошибке
 * @returns {ReactElement}
 */
const ErrorInfo: FC<IErrorInfo & IComponentBaseProps> = ({
  baseClass = "errorInfo",
  extraClasses = {},
  extraAttrs = {},
  children = null,
  error = "Произошла ошибка при загрузке компонента. =/",
}): ReactElement => {

  const { getCN } = useCN(baseClass);

  const getParsedError = useCallback((err: string | Error | Array<string | Error>) => {
    switch (true) {
      case Array.isArray(err):
        return err.map((item) => isErrorInstance(item) ? (item.message || item.toString()) : item).join("\n");
      case isErrorInstance(err):
        return err.message || err.toString();
      case typeof err === "string":
      default:
        return err;
    }
  }, [ error ]);

  return (
    <div className={getCN("", extraClasses)} {...extraAttrs} role={"alert"}>
      {children || (!!error && <pre className={getCN("data")}>
        {getParsedError(error)}
      </pre>)}
    </div>
  );

};

export type { IErrorInfo };
export { ErrorInfo };
