import React, { useState, useEffect, ReactNode } from 'react';
import NetInfo, { useNetInfo } from '@react-native-community/netinfo';
import OfflineScreen from '@/components/OfflineScreen';

interface NetworkProviderProps {
    children: ReactNode;
}

export const NetworkProvider = ({ children }: NetworkProviderProps) => {
    const netInfo = useNetInfo();
    const [isOffline, setIsOffline] = useState(false);
    const [isRetrying, setIsRetrying] = useState(false);

    useEffect(() => {
        if (netInfo.isConnected === false) {
            setIsOffline(true);
        } else {
            setIsOffline(false);
        }
    }, [netInfo.isConnected]);

    // Manual Retry Handler
    const handleManualRetry = async () => {
        setIsRetrying(true);

        const state = await NetInfo.fetch();
        setTimeout(() => {
            setIsOffline(state.isConnected === false);
            setIsRetrying(false);
        }, 1000);
    };

    if (isOffline) {
        return (
            <OfflineScreen
                onRetry={handleManualRetry}
                isRetrying={isRetrying}
            />
        );
    }
    return <>{children}</>;
};