import React, { Component } from 'react';
import { AlertTriangle, RefreshCw } from 'lucide-react';

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

    static getDerivedStateFromError(error) {
        // Update state so the next render will show the fallback UI.
        return { hasError: true, error };
    }

    componentDidCatch(error, errorInfo) {
        // You can also log the error to an error reporting service
        console.error("Uncaught error:", error, errorInfo);
    }

    handleReload = () => {
        window.location.reload();
    };

    render() {
        if (this.state.hasError) {
            // Custom Fallback UI
            return (
                <div className="min-h-screen bg-zinc-50 dark:bg-zinc-950 flex flex-col items-center justify-center p-6 text-center">
                    <div className="w-16 h-16 bg-red-100 dark:bg-red-900/30 rounded-full flex items-center justify-center mb-6">
                        <AlertTriangle size={32} className="text-red-500" />
                    </div>

                    <h1 className="text-3xl font-black text-zinc-900 dark:text-white mb-2 tracking-tight">
                        Something went wrong
                    </h1>

                    <p className="text-zinc-500 dark:text-zinc-400 max-w-md mb-8">
                        We encountered an unexpected error. Our team has been notified. Please try refreshing the page.
                    </p>

                    <div className="p-4 bg-zinc-100 dark:bg-white/5 rounded-xl border border-zinc-200 dark:border-white/10 max-w-lg w-full mb-8 text-left font-mono text-xs text-red-500 overflow-auto max-h-40">
                        {this.state.error && this.state.error.toString()}
                    </div>

                    <button
                        onClick={this.handleReload}
                        className="flex items-center space-x-2 px-6 py-3 bg-zinc-900 dark:bg-white text-white dark:text-black font-bold rounded-full hover:opacity-90 transition-opacity"
                    >
                        <RefreshCw size={18} />
                        <span>Reload Application</span>
                    </button>
                </div>
            );
        }

        return this.props.children;
    }
}

export default ErrorBoundary;
