import { Component, ReactNode, ErrorInfo } from 'react';
import { AlertTriangle, RefreshCw, Home } from 'lucide-react';
import { monitoring } from '../lib/monitoring';

interface Props {
    children: ReactNode;
    fallback?: ReactNode;
}

interface State {
    hasError: boolean;
    error: Error | null;
    errorInfo: ErrorInfo | null;
}

export class ErrorBoundary extends Component<Props, State> {
    constructor(props: Props) {
        super(props);
        this.state = { hasError: false, error: null, errorInfo: null };
    }

    static getDerivedStateFromError(error: Error): Partial<State> {
        return { hasError: true, error };
    }

    componentDidCatch(error: Error, errorInfo: ErrorInfo) {
        this.setState({ errorInfo });

        // Log to console in development
        console.error('ErrorBoundary caught an error:', error, errorInfo);

        // Send to monitoring service
        monitoring.logComponentError(error, errorInfo.componentStack || '');
    }

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

    handleGoHome = () => {
        window.location.href = '/';
    };

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

            return (
                <div className="min-h-screen bg-[var(--color-bg-tertiary)] flex items-center justify-center p-6">
                    <div className="max-w-md w-full bg-[var(--color-bg-elevated)] rounded-2xl shadow-xl p-8 text-center">
                        <div className="w-16 h-16 mx-auto bg-red-100 dark:bg-red-900/30 rounded-full flex items-center justify-center mb-6">
                            <AlertTriangle size={32} className="text-red-600 dark:text-red-400" />
                        </div>

                        <h1 className="text-2xl font-bold text-[var(--color-text-primary)] mb-2">
                            Something went wrong
                        </h1>

                        <p className="text-[var(--color-text-tertiary)] mb-6">
                            An unexpected error occurred. Don't worry, your data is safe.
                        </p>

                        {/* Error Details (collapsible in production) */}
                        {import.meta.env.DEV && this.state.error && (
                            <details className="mb-6 text-left">
                                <summary className="cursor-pointer text-sm text-[var(--color-text-tertiary)] hover:text-slate-700 dark:hover:text-slate-300">
                                    Technical Details
                                </summary>
                                <pre className="mt-2 p-3 bg-[var(--color-bg-tertiary)] rounded-lg text-xs text-red-600 dark:text-red-400 overflow-auto max-h-32">
                                    {this.state.error.toString()}
                                    {this.state.errorInfo?.componentStack}
                                </pre>
                            </details>
                        )}

                        <div className="flex gap-3">
                            <button
                                onClick={this.handleRetry}
                                className="flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-[var(--color-primary)] hover:bg-[var(--color-primary-hover)] text-white font-medium rounded-xl transition-colors"
                            >
                                <RefreshCw size={18} />
                                Try Again
                            </button>
                            <button
                                onClick={this.handleGoHome}
                                className="flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-slate-200 dark:bg-slate-700 hover:bg-slate-300 dark:hover:bg-slate-600 text-[var(--color-text-secondary)]late-200 font-medium rounded-xl transition-colors"
                            >
                                <Home size={18} />
                                Go Home
                            </button>
                        </div>
                    </div>
                </div>
            );
        }

        return this.props.children;
    }
}

// Convenience wrapper for specific sections
export function SectionErrorBoundary({ children, name }: { children: ReactNode; name: string }) {
    return (
        <ErrorBoundary
            fallback={
                <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-xl p-6 text-center">
                    <AlertTriangle className="mx-auto text-red-500 mb-2" size={24} />
                    <p className="text-red-700 dark:text-red-400 font-medium">
                        Failed to load {name}
                    </p>
                    <button
                        onClick={() => window.location.reload()}
                        className="mt-3 text-sm text-red-600 dark:text-red-400 hover:underline"
                    >
                        Reload Page
                    </button>
                </div>
            }
        >
            {children}
        </ErrorBoundary>
    );
}
