import React, { createContext, useState, useEffect, ReactNode } from 'react';
import { Linking, Platform } from 'react-native';
import Constants from 'expo-constants';
import axios from 'axios';
import LoadingScreen from '@/components/LoadingScreen';
import UpdateScreen from '@/components/UpdateScreen';
import { isUpdateAvailable } from '@/utils/version';
import { setApiBaseUrl } from './api';

interface ConfigContextProps {
    children: ReactNode
};

// Context (useful if you want to trigger manual checks from inside the app in the future)
export const ConfigContext = createContext({});

const GW_API = process.env.EXPO_PUBLIC_GW_API_URL;
const GW_UUID = process.env.EXPO_PUBLIC_GW_UUID;
const GW_TOKEN = process.env.EXPO_PUBLIC_GW_API_TOKEN;

export const ConfigProvider = ({ children }: ConfigContextProps) => {
    const [isChecking, setIsChecking] = useState(true);
    const [needsUpdate, setNeedsUpdate] = useState(false);
    const [updateUrl, setUpdateUrl] = useState('');

    useEffect(() => {
        const checkAppVersion = async () => {
            try {

                const apiUrl = `${GW_API}${GW_UUID}`;
                const response = await axios.get(apiUrl, {
                    headers: { "x-access-tokens": GW_TOKEN }
                });

                // Update API URL: prioritize environment variable (override) over gateway response
                setApiBaseUrl(process.env.EXPO_PUBLIC_API_URL || response.data.url);

                const currentVersion = Constants.expoConfig?.version;
                console.log("Versione attuale dell'app:", currentVersion);

                const latestVersion = response.data.version;
                console.log("Versione più recente disponibile:", latestVersion);
                
                // Check if an update is needed
                if (isUpdateAvailable(currentVersion, latestVersion)) {
                    setNeedsUpdate(true);
                    setUpdateUrl(Platform.OS === 'ios' ? response.data.app_url_ios : response.data.app_url_android);
                }

            } catch (error) {
                console.error("Errore durante il controllo della versione:", error);
                setNeedsUpdate(false);
            } finally {
                setIsChecking(false);
            }
        };

        checkAppVersion();
    }, []);

    const handleUpdate = async () => {
        if (updateUrl) {
            Linking.openURL(updateUrl);
        }
    };

    // Loading state
    if (isChecking) {
        return (
            <LoadingScreen />
        );
    }

    // Update state: blocks children rendering
    if (needsUpdate) {
        return (
            <UpdateScreen onUpdate={handleUpdate} />
        );
    }

    // Version is up to date
    return (
        <ConfigContext.Provider value={{ isChecking, needsUpdate }}>
            {children}
        </ConfigContext.Provider>
    );
};
