import React, { Component, ErrorInfo, ReactNode } from "react";

interface Props {
    children: ReactNode;
}

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

export class ErrorBoundary extends Component<Props, State> {
    public state: State = {
        hasError: false,
        error: null,
    };

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

    public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
        console.error("Uncaught error:", error, errorInfo);
    }

    public render() {
        if (this.state.hasError) {
            return (
                <div className="min-h-screen flex items-center justify-center p-4 bg-red-50 text-red-900">
                    <div className="max-w-xl p-8 bg-white rounded-lg shadow-xl border border-red-200">
                        <h1 className="text-2xl font-bold mb-4">Something went wrong</h1>
                        <p className="mb-4">The application crashed. Here is the error:</p>
                        <pre className="bg-red-100 p-4 rounded overflow-auto text-sm font-mono">
                            {this.state.error?.toString()}
                        </pre>
                        <button
                            className="mt-6 px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700"
                            onClick={() => window.location.reload()}
                        >
                            Reload Page
                        </button>
                    </div>
                </div>
            );
        }

        return this.props.children;
    }
}
