import React, { Component, ReactNode } from 'react'

interface ErrorBoundaryProps {
  children: ReactNode
  fallback?: ReactNode
}

interface ErrorBoundaryState {
  hasError: boolean
  error?: Error
}

class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
  constructor(props: ErrorBoundaryProps) {
    super(props)
    this.state = { hasError: false }
  }

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

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    console.error('组件渲染错误:', error)
    console.error('错误信息:', errorInfo.componentStack)
  }

  render() {
    if (this.state.hasError) {
      if (this.props.fallback) {
        return this.props.fallback
      }

      return (
        <div style={{
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
          minHeight: '400px',
          padding: '40px',
          textAlign: 'center',
          backgroundColor: '#fff',
          borderRadius: '8px',
          boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
        }}>
          <div style={{ fontSize: '48px', color: '#ff4d4f', marginBottom: '16px' }}>⚠️</div>
          <h3 style={{ color: '#333', marginBottom: '12px' }}>页面加载出错</h3>
          <p style={{ color: '#666', marginBottom: '24px', maxWidth: '500px' }}>
            抱歉，页面渲染时发生了错误。请尝试刷新页面或联系管理员。
          </p>
          {this.state.error && (
            <div style={{
              marginTop: '16px',
              padding: '12px',
              backgroundColor: '#f5f5f5',
              borderRadius: '4px',
              fontSize: '12px',
              color: '#999',
              textAlign: 'left',
              maxWidth: '600px',
              overflow: 'auto'
            }}>
              <div><strong>错误信息:</strong> {this.state.error.message}</div>
              {this.state.error.stack && (
                <div style={{ marginTop: '8px' }}>
                  <strong>错误堆栈:</strong>
                  <pre style={{ margin: '8px 0', whiteSpace: 'pre-wrap' }}>
                    {this.state.error.stack}
                  </pre>
                </div>
              )}
            </div>
          )}
          <div style={{ marginTop: '24px' }}>
            <button
              onClick={() => window.location.reload()}
              style={{
                padding: '8px 24px',
                backgroundColor: '#1890ff',
                color: '#fff',
                border: 'none',
                borderRadius: '4px',
                cursor: 'pointer',
                fontSize: '14px'
              }}
            >
              刷新页面
            </button>
          </div>
        </div>
      )
    }

    return this.props.children
  }
}

export default ErrorBoundary