import { Component } from 'react'

/**
 * Verhindert, dass ein fehlerhaftes Dashboard-Widget die ganze Seite mitreißt.
 */
export default class WidgetErrorBoundary extends Component {
  constructor(props) {
    super(props)
    this.state = { error: null }
  }

  static getDerivedStateFromError(error) {
    return { error }
  }

  render() {
    if (this.state.error) {
      const msg =
        this.state.error && typeof this.state.error === 'object' && 'message' in this.state.error
          ? String(this.state.error.message)
          : String(this.state.error)
      return (
        <div
          className="card section-gap"
          style={{ marginBottom: 16, borderColor: 'var(--danger, #D85A30)' }}
        >
          <div className="card-title" style={{ color: 'var(--danger, #D85A30)' }}>
            Widget-Fehler
          </div>
          <p style={{ fontSize: 12, color: 'var(--text2)', margin: '4px 0 8px' }}>
            <code>{this.props.widgetId}</code>
          </p>
          <pre
            style={{
              fontSize: 11,
              overflow: 'auto',
              margin: 0,
              padding: 8,
              background: 'var(--surface2)',
              borderRadius: 8,
              color: 'var(--text2)',
            }}
          >
            {msg}
          </pre>
        </div>
      )
    }
    return this.props.children
  }
}
