import { Component, ReactNode } from 'react';
import { IS_DEV } from '@/config';
import { Lang } from '@/lang/Lang';

interface ErrorBoundaryProps {
    children: ReactNode;
}

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

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) {
        if (IS_DEV) {
            console.error('ErrorBoundary caught an error:', error, errorInfo);
        }
    }

    render() {
        if (this.state.hasError) {
            return (
                <div className='text-red-500 text-xs p-2 bg-red-200 rounded-md px-4'>
                    {Lang.key('error_please_go_to_support')}
                    {IS_DEV && this.state.error && (
                        <div className='mt-2 text-red-700 font-mono text-[10px] break-all'>
                            {this.state.error.toString()}
                        </div>
                    )}
                </div>
            );
        }
        return this.props.children;
    }
}
