import { Component, type ReactNode } from "react"
import i18n from "@/i18n"

interface Props {
  children: ReactNode
  fallback?: ReactNode
}

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

export 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 }
  }

  componentDidCatch(error: Error, info: React.ErrorInfo) {
    console.error("ErrorBoundary caught:", error, info.componentStack)
  }

  render() {
    if (this.state.hasError) {
      if (this.props.fallback) return this.props.fallback
      return (
        <div className="flex h-full flex-col items-center justify-center gap-3 p-6 text-sm text-muted-foreground">
          <p className="text-destructive font-medium">{i18n.t("errors.generic")}</p>
          <p className="text-xs max-w-md text-center">{this.state.error?.message}</p>
          <button
            className="rounded border px-3 py-1 text-xs hover:bg-muted"
            onClick={() => this.setState({ hasError: false, error: null })}
          >
            {i18n.t("common.retry")}
          </button>
        </div>
      )
    }
    return this.props.children
  }
}
