/**
 * 全局错误边界 — 捕获 React 渲染异常，显示错误信息而非白屏。
 */

import React from "react";
import { Result, Button, Typography } from "antd";

const { Paragraph, Text } = Typography;

interface Props {
  children: React.ReactNode;
}

interface State {
  hasError: boolean;
  error: Error | null;
}

class ErrorBoundary extends React.Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = { hasError: false, error: null };
  }

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

  componentDidCatch(error: Error, info: React.ErrorInfo) {
    console.error("[ErrorBoundary]", error, info.componentStack);
  }

  handleReload = () => {
    this.setState({ hasError: false, error: null });
    window.location.reload();
  };

  render() {
    if (this.state.hasError) {
      return (
        <div style={{ padding: 48 }}>
          <Result
            status="error"
            title="页面渲染出错"
            subTitle="请尝试刷新页面，如果问题持续请联系管理员。"
            extra={
              <Button type="primary" onClick={this.handleReload}>
                刷新页面
              </Button>
            }
          >
            {this.state.error && (
              <Paragraph>
                <Text type="danger" code style={{ whiteSpace: "pre-wrap", wordBreak: "break-all" }}>
                  {this.state.error.message}
                </Text>
              </Paragraph>
            )}
          </Result>
        </div>
      );
    }

    return this.props.children;
  }
}

export default ErrorBoundary;
