import { Component, type ReactNode } from 'react'

interface Props { children: ReactNode; fallback?: ReactNode }
interface State { hasError: boolean; error: Error | null }

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

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

  render() {
    if (this.state.hasError) {
      return this.props.fallback ?? (
        <div className="flex flex-col items-center justify-center h-screen gap-2 p-8">
          <p className="text-sm font-medium text-destructive">Algo salió mal al cargar el workspace.</p>
          <p className="text-xs text-muted-foreground">{this.state.error?.message}</p>
          <button
            className="text-xs underline text-muted-foreground"
            onClick={() => window.location.reload()}
          >
            Recargar la página
          </button>
        </div>
      )
    }
    return this.props.children
  }
}
