import React from 'react'

type ErrorBoundaryState = {
  hasError: boolean
  message?: string
}

export class ErrorBoundary extends React.Component<React.PropsWithChildren, ErrorBoundaryState> {
  state: ErrorBoundaryState = { hasError: false }

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

  componentDidCatch(error: Error) {
    console.error('App runtime error:', error)
  }

  private handleReset = () => {
    try {
      localStorage.removeItem('smart-agenda')
    } catch (err) {
      console.error('Failed to clear local storage', err)
    }
    window.location.reload()
  }

  render() {
    if (!this.state.hasError) return this.props.children

    return (
      <div className="min-h-screen bg-slate-50 text-slate-900 px-4 py-10">
        <div className="mx-auto max-w-xl rounded-xl border border-slate-200 bg-white p-6 shadow-sm space-y-4">
          <h1 className="text-xl font-semibold">A aplicação encontrou um erro</h1>
          <p className="text-sm text-slate-600">
            Vamos recuperar o estado local e recarregar a página.
          </p>
          {this.state.message ? (
            <pre className="rounded-md bg-slate-100 p-3 text-xs text-slate-700 overflow-auto">
              {this.state.message}
            </pre>
          ) : null}
          <button
            type="button"
            onClick={this.handleReset}
            className="inline-flex items-center justify-center rounded-md bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700"
          >
            Limpar dados locais e recarregar
          </button>
        </div>
      </div>
    )
  }
}
