import { useState, useEffect, useCallback, createContext, useContext } from 'react';

interface Toast {
    id: string;
    type: 'success' | 'error' | 'warning' | 'info' | 'confirm';
    title: string;
    message?: string;
    duration?: number;
    onConfirm?: () => void;
    onCancel?: () => void;
}

interface ToastContextType {
    toasts: Toast[];
    addToast: (toast: Omit<Toast, 'id'>) => string;
    removeToast: (id: string) => void;
    confirm: (title: string, message?: string) => Promise<boolean>;
}

const ToastContext = createContext<ToastContextType | null>(null);

export function useToast() {
    const context = useContext(ToastContext);
    if (!context) throw new Error('useToast must be used within ToastProvider');
    return context;
}

export function ToastProvider({ children }: { children: React.ReactNode }) {
    const [toasts, setToasts] = useState<Toast[]>([]);

    const addToast = useCallback((toast: Omit<Toast, 'id'>) => {
        const id = Math.random().toString(36).substr(2, 9);
        setToasts(prev => [...prev, { ...toast, id }]);

        // Auto-remove non-confirm toasts
        if (toast.type !== 'confirm' && toast.duration !== 0) {
            setTimeout(() => {
                setToasts(prev => prev.filter(t => t.id !== id));
            }, toast.duration || 3000);
        }

        return id;
    }, []);

    const removeToast = useCallback((id: string) => {
        setToasts(prev => prev.filter(t => t.id !== id));
    }, []);

    const confirm = useCallback((title: string, message?: string): Promise<boolean> => {
        return new Promise((resolve) => {
            const id = Math.random().toString(36).substr(2, 9);
            setToasts(prev => [...prev, {
                id,
                type: 'confirm',
                title,
                message,
                onConfirm: () => {
                    setToasts(prev => prev.filter(t => t.id !== id));
                    resolve(true);
                },
                onCancel: () => {
                    setToasts(prev => prev.filter(t => t.id !== id));
                    resolve(false);
                }
            }]);
        });
    }, []);

    return (
        <ToastContext.Provider value={{ toasts, addToast, removeToast, confirm }}>
            {children}
            <ToastContainer toasts={toasts} removeToast={removeToast} />
        </ToastContext.Provider>
    );
}

function ToastContainer({ toasts, removeToast }: { toasts: Toast[], removeToast: (id: string) => void }) {
    if (toasts.length === 0) return null;

    return (
        <div className="fixed inset-0 z-[100] pointer-events-none flex flex-col items-center justify-start p-4 pt-8 gap-3">
            {toasts.map(toast => (
                <ToastItem key={toast.id} toast={toast} onDismiss={() => removeToast(toast.id)} />
            ))}
        </div>
    );
}

function ToastItem({ toast, onDismiss }: { toast: Toast, onDismiss: () => void }) {
    const [isVisible, setIsVisible] = useState(false);

    useEffect(() => {
        // Trigger animation
        requestAnimationFrame(() => setIsVisible(true));
    }, []);

    const typeStyles = {
        success: 'border-l-4 border-l-green-500',
        error: 'border-l-4 border-l-red-500',
        warning: 'border-l-4 border-l-yellow-500',
        info: 'border-l-4 border-l-blue-500',
        confirm: 'border-l-4 border-l-blue-500'
    };

    const typeIcons = {
        success: (
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                <circle cx="12" cy="12" r="10" fill="#34C759" />
                <path d="m8 12 3 3 5-6" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
        ),
        error: (
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                <circle cx="12" cy="12" r="10" fill="#FF3B30" />
                <path d="M15 9l-6 6M9 9l6 6" stroke="white" strokeWidth="2" strokeLinecap="round" />
            </svg>
        ),
        warning: (
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                <path d="M12 2L2 22h20L12 2z" fill="#FF9500" />
                <path d="M12 10v4M12 17h.01" stroke="white" strokeWidth="2" strokeLinecap="round" />
            </svg>
        ),
        info: (
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                <circle cx="12" cy="12" r="10" fill="#007AFF" />
                <path d="M12 8h.01M12 12v4" stroke="white" strokeWidth="2" strokeLinecap="round" />
            </svg>
        ),
        confirm: (
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                <circle cx="12" cy="12" r="10" fill="#007AFF" />
                <path d="M12 8h.01M12 12v4" stroke="white" strokeWidth="2" strokeLinecap="round" />
            </svg>
        )
    };

    return (
        <div
            className={`
                pointer-events-auto
                liquid-glass-heavy
                rounded-[var(--radius-lg)]
                shadow-xl
                max-w-md w-full
                transform transition-all duration-300 ease-out
                ${isVisible ? 'translate-y-0 opacity-100' : '-translate-y-4 opacity-0'}
                ${typeStyles[toast.type]}
            `}
        >
            <div className="p-4 flex items-start gap-3">
                <div className="shrink-0 mt-0.5">
                    {typeIcons[toast.type]}
                </div>
                <div className="flex-1 min-w-0">
                    <div className="font-semibold text-[14px] text-gray-900">{toast.title}</div>
                    {toast.message && (
                        <div className="text-[13px] text-gray-600 mt-0.5">{toast.message}</div>
                    )}

                    {toast.type === 'confirm' && (
                        <div className="flex gap-2 mt-3">
                            <button
                                onClick={toast.onCancel}
                                className="px-4 py-1.5 liquid-glass rounded-[var(--radius-sm)] text-[13px] font-medium glass-hover glass-press"
                            >
                                Cancel
                            </button>
                            <button
                                onClick={toast.onConfirm}
                                className="px-4 py-1.5 bg-gradient-to-b from-[#1E90FF] to-[#007AFF] text-white rounded-[var(--radius-sm)] text-[13px] font-medium shadow-lg glass-press"
                            >
                                Confirm
                            </button>
                        </div>
                    )}
                </div>

                {toast.type !== 'confirm' && (
                    <button
                        onClick={onDismiss}
                        className="shrink-0 text-gray-400 hover:text-gray-600 transition-colors p-1"
                    >
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                            <path d="M18 6L6 18M6 6l12 12" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
                        </svg>
                    </button>
                )}
            </div>
        </div>
    );
}
