import { Component, ReactNode } from "react";

interface ErrorBoundaryProps {
  errorChildren?: JSX.Element | ReactNode;
  children?: JSX.Element | ReactNode;
  reloadOnError?: boolean;
}

class ErrorBoundary extends Component<
  ErrorBoundaryProps,
  { hasError: boolean }
> {
  constructor(props: ErrorBoundaryProps) {
    super(props);
    this.state = { hasError: false };
  }
  static getDerivedStateFromError(error: unknown) {
    console.error(error); // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }
  // You can also log the error to an error reporting service here
  componentDidCatch(error: unknown, errorInfo: unknown) {
    console.error(error);
    console.error(errorInfo);
  }
  render() {
    if (this.state.hasError) {
      if (this.props.reloadOnError) window.location.reload();
      return (
        this.props.errorChildren ?? (
          <span>
            An error occurred causing failure to load this component.
            <br />
            Check console for more details.
          </span>
        )
      );
    }

    return this.props.children;
  }
}

export default ErrorBoundary;
