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

interface Props {
  children: ReactNode
  fallback?: ReactNode
}

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

export class ErrorBoundary extends 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, errorInfo: ErrorInfo): void {
    // eslint-disable-next-line no-console -- React error boundary standard pattern
    console.error('ErrorBoundary caught an error:', error, errorInfo)
  }

  handleReset = (): void => {
    this.setState({ hasError: false, error: null })
  }

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

      const isDev =
        (typeof import.meta !== 'undefined' &&
          (import.meta as { env?: { DEV?: boolean } }).env?.DEV) ??
        false

      return (
        <div className="error-boundary-root" role="alert">
          <h2 className="error-boundary-title">应用遇到了错误</h2>
          {isDev && (
            <pre className="error-boundary-detail">
              {this.state.error?.message}
            </pre>
          )}
          <button className="error-boundary-reset" onClick={this.handleReset}>
            重试
          </button>
        </div>
      )
    }

    return this.props.children
  }
}
