import * as React from 'react'

export interface ErrorBoundaryProps {
  children: React.ReactNode
  /** Static fallback element, or a function that receives the error */
  fallback: React.ReactNode | ((error: Error) => React.ReactNode)
  /** Callback when an error is caught */
  onError?: (error: Error, errorInfo: React.ErrorInfo) => void
}

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

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

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

  override componentDidCatch(error: Error, errorInfo: React.ErrorInfo): void {
    this.props.onError?.(error, errorInfo)
  }

  override render(): React.ReactNode {
    if (this.state.hasError && this.state.error !== null) {
      const { fallback } = this.props
      if (typeof fallback === 'function') {
        return fallback(this.state.error)
      }
      return fallback
    }
    return this.props.children
  }
}
