import React, { useState, useCallback } from 'react';
import type { ReactNode } from 'react';
import { ShieldAlert } from 'lucide-react';
import { setGlobalToastHandler } from '../utils/toastHandler';
import { ToastContext } from '../context/ToastContext';
import type { Toast } from '../context/ToastContext';

interface ToastProviderProps {
    children: ReactNode;
}

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

    const showToast = useCallback((message: string, type: Toast['type'] = 'warning') => {
        const id = Date.now().toString();
        setToasts((prev) => [...prev, { id, message, type }]);

        // Auto-remove after 3 seconds
        setTimeout(() => {
            setToasts((prev) => prev.filter((t) => t.id !== id));
        }, 3000);
    }, []);

    const showGuestWarning = useCallback(() => {
        showToast('Você é um convidado e não possui permissão para esta ação', 'warning');
    }, [showToast]);

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

    // Register global handler
    React.useEffect(() => {
        setGlobalToastHandler(showGuestWarning);
        return () => setGlobalToastHandler(() => { });
    }, [showGuestWarning]);

    return (
        <ToastContext.Provider value={{ showToast, showGuestWarning }}>
            {children}

            {/* Toast Container - Centered */}
            {toasts.length > 0 && (
                <div className="fixed inset-0 flex items-center justify-center pointer-events-none z-[100]">
                    <div className="flex flex-col gap-3">
                        {toasts.map((toast) => (
                            <div
                                key={toast.id}
                                onClick={() => removeToast(toast.id)}
                                className="pointer-events-auto animate-in fade-in zoom-in duration-200 bg-gradient-to-r from-amber-500/95 to-orange-500/95 text-white px-8 py-5 rounded-2xl shadow-2xl shadow-amber-500/30 flex flex-col items-center justify-center text-center max-w-sm backdrop-blur-sm cursor-pointer hover:scale-[1.02] transition-transform"
                            >
                                <div className="bg-white/20 p-3 rounded-xl mb-3">
                                    <ShieldAlert size={28} />
                                </div>
                                <p className="font-bold text-base mb-1">Acesso Restrito</p>
                                <p className="text-white/90 text-base leading-relaxed">{toast.message}</p>
                            </div>
                        ))}
                    </div>
                </div>
            )}
        </ToastContext.Provider>
    );
};
