"use client"

import { Component, ReactNode } from 'react'
import Link from 'next/link'

interface Props {
  children: ReactNode
}

interface State {
  hasError: boolean
  error?: Error
}

export default class ErrorBoundary extends Component<Props, State> {
  constructor(props: Props) {
    super(props)
    this.state = { hasError: false }
  }

  static getDerivedStateFromError(error: Error): State {
    return { hasError: true, error }
  }

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    console.error('ErrorBoundary caught an error:', error, errorInfo)
  }

  handleRetry = () => {
    this.setState({ hasError: false, error: undefined })
    window.location.reload()
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="min-h-screen bg-[#f4f7fb] flex flex-col items-center justify-center px-6">
          <div className="text-center max-w-md">
            <h1
              className="text-4xl font-bold text-[#102443] mb-4"
            >
              Something went wrong
            </h1>
            <p
              className="text-[#4a5565] text-lg mb-8"
            >
              We encountered an unexpected error. Please try refreshing the page.
            </p>
            <div className="flex gap-4 justify-center">
              <button
                onClick={this.handleRetry}
                className="px-6 py-3 bg-[#d20010] text-white rounded-full hover:bg-[#b8000e] transition-colors"
              >
                Refresh Page
              </button>
              <Link
                href="/"
                className="px-6 py-3 bg-white text-[#102443] rounded-full border border-[#e5e7eb] hover:bg-gray-50 transition-colors"
              >
                Go Home
              </Link>
            </div>
          </div>
        </div>
      )
    }

    return this.props.children
  }
}
