import React, { createContext, useContext, useState, ReactNode, useCallback, useRef } from 'react';

interface AlertConfig {
    type: 'success' | 'error' | 'warning' | 'info';
    title: string;
    message: string;
}

interface ConfirmConfig {
    title: string;
    message: string;
}

interface AlertContextType {
    showAlert: (config: AlertConfig) => void;
    showConfirm: (config: ConfirmConfig) => Promise<boolean>;
}

const AlertContext = createContext<AlertContextType | undefined>(undefined);

export const useAlert = () => {
    const context = useContext(AlertContext);
    if (!context) {
        throw new Error('useAlert must be used within AlertProvider');
    }
    return context;
};

interface AlertProviderProps {
    children: ReactNode;
}

export const AlertProvider: React.FC<AlertProviderProps> = ({ children }) => {
    const [alertConfig, setAlertConfig] = useState<(AlertConfig & { isOpen: boolean }) | null>(null);
    const [confirmConfig, setConfirmConfig] = useState<(ConfirmConfig & { isOpen: boolean }) | null>(null);
    const confirmResolveRef = useRef<((value: boolean) => void) | null>(null);

    const showAlert = (config: AlertConfig) => {
        setAlertConfig({ ...config, isOpen: true });
    };

    const closeAlert = () => {
        setAlertConfig(null);
    };

    const showConfirm = useCallback((config: ConfirmConfig): Promise<boolean> => {
        return new Promise((resolve) => {
            confirmResolveRef.current = resolve;
            setConfirmConfig({ ...config, isOpen: true });
        });
    }, []);

    const handleConfirm = (result: boolean) => {
        setConfirmConfig(null);
        if (confirmResolveRef.current) {
            confirmResolveRef.current(result);
            confirmResolveRef.current = null;
        }
    };

    return (
        <AlertContext.Provider value={{ showAlert, showConfirm }}>
            {children}
            {/* Alert Dialog */}
            {alertConfig && (
                <div className="fixed inset-0 z-[100] flex items-center justify-center">
                    {/* Backdrop */}
                    <div
                        className="absolute inset-0 bg-black/80 backdrop-blur-sm"
                        onClick={closeAlert}
                    />

                    {/* Dialog */}
                    <div
                        className={`relative bg-black/95 backdrop-blur-md border-2 ${getBorderColor(alertConfig.type)} rounded-lg shadow-2xl max-w-md w-full mx-4 animate-fadeIn`}
                    >
                        {/* Icon and Title */}
                        <div className="flex items-center gap-4 p-6 border-b border-white/10">
                            {getIcon(alertConfig.type)}
                            <h2 className="text-xl font-tech font-bold text-white uppercase tracking-wider">
                                {alertConfig.title}
                            </h2>
                        </div>

                        {/* Message */}
                        <div className="p-6 max-w-full overflow-hidden">
                            <p className="text-slate-300 font-mono text-sm whitespace-pre-wrap leading-relaxed break-words max-w-full">
                                {alertConfig.message}
                            </p>
                        </div>

                        {/* Button */}
                        <div className="flex justify-end p-6 border-t border-white/10">
                            <button
                                onClick={closeAlert}
                                className="px-6 py-2 bg-neon-blue/20 hover:bg-neon-blue/30 border border-neon-blue text-neon-blue font-tech font-bold rounded transition-colors shadow-glow-blue"
                            >
                                OK
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {/* Confirm Dialog */}
            {confirmConfig && (
                <div className="fixed inset-0 z-[100] flex items-center justify-center">
                    {/* Backdrop */}
                    <div
                        className="absolute inset-0 bg-black/80 backdrop-blur-sm"
                        onClick={() => handleConfirm(false)}
                    />

                    {/* Dialog */}
                    <div className="relative bg-black/95 backdrop-blur-md border-2 border-amber-500 rounded-lg shadow-2xl max-w-md w-full mx-4 animate-fadeIn">
                        {/* Icon and Title */}
                        <div className="flex items-center gap-4 p-6 border-b border-white/10">
                            <svg className="w-12 h-12 text-amber-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                            </svg>
                            <h2 className="text-xl font-tech font-bold text-white uppercase tracking-wider">
                                {confirmConfig.title}
                            </h2>
                        </div>

                        {/* Message */}
                        <div className="p-6 max-w-full overflow-hidden">
                            <p className="text-slate-300 font-mono text-sm whitespace-pre-wrap leading-relaxed break-words max-w-full">
                                {confirmConfig.message}
                            </p>
                        </div>

                        {/* Buttons */}
                        <div className="flex justify-end gap-3 p-6 border-t border-white/10">
                            <button
                                onClick={() => handleConfirm(false)}
                                className="px-6 py-2 bg-slate-700 hover:bg-slate-600 border border-white/20 text-white font-tech font-bold rounded transition-colors"
                            >
                                No
                            </button>
                            <button
                                onClick={() => handleConfirm(true)}
                                className="px-6 py-2 bg-amber-500/20 hover:bg-amber-500/30 border border-amber-500 text-amber-400 font-tech font-bold rounded transition-colors"
                            >
                                Yes
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </AlertContext.Provider>
    );
};

const getIcon = (type: 'success' | 'error' | 'warning' | 'info') => {
    const icons = {
        success: (
            <svg className="w-12 h-12 text-green-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
        ),
        error: (
            <svg className="w-12 h-12 text-red-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
        ),
        warning: (
            <svg className="w-12 h-12 text-amber-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
            </svg>
        ),
        info: (
            <svg className="w-12 h-12 text-blue-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
        ),
    };
    return icons[type];
};

const getBorderColor = (type: 'success' | 'error' | 'warning' | 'info') => {
    const colors = {
        success: 'border-green-500',
        error: 'border-red-500',
        warning: 'border-amber-500',
        info: 'border-blue-500',
    };
    return colors[type];
};
