"use client"

import { Component } from "react"
import { AlertCircle, RefreshCw } from "lucide-react"

import type { ErrorInfo, ReactNode } from "react"

import { ApiError } from "@/lib/api-client"

import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"

interface ApiErrorBoundaryProps {
  children: ReactNode
  fallbackMessage?: string
}

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

export class ApiErrorBoundary extends Component<
  ApiErrorBoundaryProps,
  ApiErrorBoundaryState
> {
  constructor(props: ApiErrorBoundaryProps) {
    super(props)
    this.state = { hasError: false, error: null }
  }

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

  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    console.error("[ApiErrorBoundary]", error, errorInfo)
  }

  handleRetry = () => {
    this.setState({ hasError: false, error: null })
  }

  render() {
    if (this.state.hasError) {
      const error = this.state.error
      const isApiError = error instanceof ApiError
      const message = isApiError
        ? error.message
        : this.props.fallbackMessage || "An unexpected error occurred."

      return (
        <Card className="mx-auto mt-8 max-w-md">
          <CardContent className="flex flex-col items-center gap-4 p-6 text-center">
            <AlertCircle className="text-destructive h-10 w-10" />
            <div className="space-y-1">
              <p className="text-sm font-medium">{message}</p>
              {isApiError && error.code !== "NETWORK_ERROR" && (
                <p className="text-muted-foreground text-xs">
                  Code: {error.code} (HTTP {error.status})
                </p>
              )}
            </div>
            <Button variant="outline" size="sm" onClick={this.handleRetry}>
              <RefreshCw className="mr-2 h-4 w-4" />
              Retry
            </Button>
          </CardContent>
        </Card>
      )
    }

    return this.props.children
  }
}
