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

interface Props {
  children: ReactNode
}

interface State {
  error: Error | null
}

export class RouteErrorBoundary extends Component<Props, State> {
  state: State = { error: null }

  static getDerivedStateFromError(error: Error): State {
    return { error }
  }

  componentDidCatch(error: Error, info: ErrorInfo) {
    console.error('Route render error:', error, info.componentStack)
  }

  render() {
    if (this.state.error) {
      return (
        <div style={{ padding: 24, maxWidth: 640 }}>
          <h2 style={{ marginBottom: 8 }}>Something went wrong</h2>
          <p style={{ color: '#b91c1c', marginBottom: 12 }}>{this.state.error.message}</p>
          <pre
            style={{
              whiteSpace: 'pre-wrap',
              fontSize: 12,
              background: 'rgba(15,23,42,0.06)',
              padding: 12,
              borderRadius: 8,
              overflow: 'auto',
            }}
          >
            {this.state.error.stack}
          </pre>
          <button
            type="button"
            style={{ marginTop: 16 }}
            onClick={() => {
              this.setState({ error: null })
              window.location.assign('/businesses')
            }}
          >
            Reload businesses
          </button>
        </div>
      )
    }

    return this.props.children
  }
}
