import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { WifiOff, Wifi } from 'lucide-react';

interface NetworkContextType {
    isOnline: boolean;
}

const NetworkContext = createContext<NetworkContextType>({ isOnline: true });

export function NetworkProvider({ children }: { children: ReactNode }) {
    const [isOnline, setIsOnline] = useState(navigator.onLine);
    const [showReconnected, setShowReconnected] = useState(false);

    useEffect(() => {
        const handleOnline = () => {
            setIsOnline(true);
            setShowReconnected(true);
            setTimeout(() => setShowReconnected(false), 3000);
        };

        const handleOffline = () => {
            setIsOnline(false);
            setShowReconnected(false);
        };

        window.addEventListener('online', handleOnline);
        window.addEventListener('offline', handleOffline);

        return () => {
            window.removeEventListener('online', handleOnline);
            window.removeEventListener('offline', handleOffline);
        };
    }, []);

    return (
        <NetworkContext.Provider value={{ isOnline }}>
            {children}

            {/* Offline Banner */}
            {!isOnline && (
                <div className="fixed top-0 left-0 right-0 z-[200] bg-red-600 text-white px-4 py-3 flex items-center justify-center gap-3 animate-slide-in shadow-lg">
                    <WifiOff size={20} />
                    <span className="font-medium">You're offline. Some features may be unavailable.</span>
                </div>
            )}

            {/* Reconnected Toast */}
            {showReconnected && (
                <div className="fixed top-4 left-1/2 -translate-x-1/2 z-[200] bg-[var(--color-primary)] text-white px-6 py-3 rounded-xl flex items-center gap-3 shadow-lg animate-scale-in">
                    <Wifi size={20} />
                    <span className="font-medium">You're back online!</span>
                </div>
            )}
        </NetworkContext.Provider>
    );
}

export function useNetwork() {
    return useContext(NetworkContext);
}
