"use client"

import { Component, ReactNode } from "react"
import { AlertCircle, RefreshCw } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"

interface ErrorBoundaryProps {
    children: ReactNode
    fallback?: ReactNode
    section?: string
}

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

/**
 * Reusable error boundary for per-section error recovery.
 * Prevents a single component crash from taking down the entire page.
 * 
 * Usage:
 * <ErrorBoundary section="Related Prompts">
 *   <RelatedPrompts ... />
 * </ErrorBoundary>
 */
export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
    constructor(props: ErrorBoundaryProps) {
        super(props)
        this.state = { hasError: false, error: null }
    }

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

    componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
        console.error(`[ErrorBoundary${this.props.section ? `: ${this.props.section}` : ''}]`, error, errorInfo)
    }

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

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

            return (
                <Card className="border-destructive/50 bg-destructive/5">
                    <CardContent className="p-6 flex flex-col items-center text-center gap-3">
                        <AlertCircle className="h-8 w-8 text-destructive" />
                        <div>
                            <h3 className="font-semibold text-sm">
                                {this.props.section ? `Error loading ${this.props.section}` : 'Something went wrong'}
                            </h3>
                            <p className="text-xs text-muted-foreground mt-1">
                                This section encountered an error. The rest of the page still works.
                            </p>
                        </div>
                        <Button
                            variant="outline"
                            size="sm"
                            onClick={this.handleRetry}
                            className="gap-2"
                        >
                            <RefreshCw className="h-3 w-3" />
                            Retry
                        </Button>
                    </CardContent>
                </Card>
            )
        }

        return this.props.children
    }
}
