"use client"

import { Component, type ReactNode } from "react"

interface ErrorBoundaryProperties {
  fallback?: ReactNode
  children: ReactNode
}

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

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

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

  render() {
    if (this.state.hasError) {
      if (this.props.fallback) {
        return this.props.fallback
      }

      return (
        <div className="flex h-full items-center justify-center p-4">
          <div className="max-w-sm text-center">
            <p className="mb-2 text-text-primary">something went wrong</p>
            <p className="mb-4 text-text-dim">
              {this.state.error?.message ?? "an unexpected error occurred"}
            </p>
            <button
              type="button"
              onClick={() => this.setState({ hasError: false, error: null })}
              className="border border-border px-3 py-1 text-text-secondary transition-colors hover:bg-background-tertiary hover:text-text-primary"
            >
              try again
            </button>
          </div>
        </div>
      )
    }

    return this.props.children
  }
}
