import { Component, type ReactNode } from 'react'
import { AlertCircle, RotateCw } from '../../lib/icons'

interface Props {
  children: ReactNode
  fallback?: ReactNode
}

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

export default class ErrorBoundary extends Component<Props, State> {
  constructor(props: Props) {
    super(props)
    this.state = { hasError: false, error: null }
  }

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

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

      return (
        <div className="flex flex-col items-center justify-center h-full min-h-[400px] p-10 text-center">
          <div className="relative w-14 h-14 mb-5">
            <div className="absolute inset-0 rounded-full bg-error/10 blur-xl" />
            <div className="relative w-full h-full rounded-full bg-error/10 grid place-items-center ring-1 ring-error/20">
              <AlertCircle size={22} className="text-error" />
            </div>
          </div>
          <h2 className="text-text-1 text-[17px] font-semibold mb-1.5 tracking-tight">Something went wrong</h2>
          <p className="text-text-3 text-[13px] mb-5 max-w-md leading-relaxed">
            {this.state.error?.message || 'An unexpected error occurred while rendering this view.'}
          </p>
          <button
            onClick={() => this.setState({ hasError: false, error: null })}
            className="h-10 px-5 bg-elevated hover:bg-higher border border-border hover:border-border-hover text-text-1 rounded-lg text-[13px] font-medium transition-all duration-200 ease-out flex items-center gap-2 focus-ring"
          >
            <RotateCw size={14} />
            Try again
          </button>
        </div>
      )
    }

    return this.props.children
  }
}
