import { Component, type ErrorInfo, type ReactNode } from 'react';
import { AlertCircle } from 'lucide-react';

type Props = {
    children: ReactNode;
    fallback?: ReactNode;
};

type State = {
    hasError: boolean;
    message: string;
};

export class ChartErrorBoundary extends Component<Props, State> {
    constructor(props: Props) {
        super(props);
        this.state = { hasError: false, message: '' };
    }

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

    componentDidCatch(error: Error, info: ErrorInfo) {
        console.error('Chart render error:', error, info.componentStack);
    }

    render() {
        if (this.state.hasError) {
            return (
                this.props.fallback ?? (
                    <div className="flex h-40 items-center justify-center gap-2 rounded-lg border border-dashed text-sm text-muted-foreground">
                        <AlertCircle className="size-4 shrink-0" />
                        <span>Chart unavailable — {this.state.message || 'render error'}</span>
                    </div>
                )
            );
        }

        return this.props.children;
    }
}
