import React, { ReactNode } from "react";
import { IconWarning } from "./icon-warning";
import "./styles.css";

interface ErrorBoundaryProps {
  children: ReactNode;
}

interface ErrorBoundaryState {
  error: Error | null;
  errorInfo: React.ErrorInfo | null;
}

class ErrorBoundary extends React.Component<
  ErrorBoundaryProps,
  ErrorBoundaryState
> {
  constructor(props: ErrorBoundaryProps) {
    super(props);
    this.state = { error: null, errorInfo: null };
  }

  static getDerivedStateFromError(error: Error): ErrorBoundaryState {
    // 触发降级 UI
    return { error, errorInfo: null };
  }

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    this.setState({ error, errorInfo });

    // 继续抛出错误，便于全局监听
    setTimeout(() => {
      throw error;
    }, 0);
  }

  render() {
    const { error, errorInfo } = this.state;
    if (error) {
      return (
        <div className="error-boundary-page">
          <div className="error-boundary-icon">
            <IconWarning />
          </div>
          <h2 className="error-boundary-title">Something went wrong</h2>
          <pre className="error-boundary-description">
            {error.toString()}
            {errorInfo && errorInfo.componentStack}
          </pre>
        </div>
      );
    }
    return this.props.children;
  }
}

export default ErrorBoundary;
