import type { ErrorInfo, ReactNode } from "react";

import { Component } from "react";
import { Alert, Button, Space } from "tdesign-react";

interface Props {
  children: ReactNode;
}

interface State {
  hasError: boolean;
}

export class ErrorBoundary extends Component<Props, State> {
  override state: State = { hasError: false };

  static getDerivedStateFromError(): State {
    return { hasError: true };
  }

  override componentDidCatch(error: Error, info: ErrorInfo): void {
    console.error("渲染错误:", error, info.componentStack);
  }

  override render() {
    if (this.state.hasError) {
      return (
        <Space align="center" className="error-boundary-fallback" direction="vertical" size="large">
          <Alert message="页面渲染出现异常，请刷新重试" theme="error" title="页面出错" />
          <Button onClick={() => window.location.reload()} theme="primary">
            刷新页面
          </Button>
        </Space>
      );
    }
    return this.props.children;
  }
}
