"use Client"
import axios from "axios";
import React, { createContext, useContext, useEffect, useState } from "react"
import DefaultState from "../utils/DefaultState";
import {debounce} from "lodash";

const GlobalContext = createContext();
const GlobalContextUpdate = createContext();

export const GlobalContextProvider = ({children}) => {
    const [state, setState] = useState();
    const [forecast, setForecast] = useState({});
    const [airPollution, setAirPollution] = useState({});
    const [dailyForecast, setDailyForecast] = useState({});
    const [uvIndex, setUvIndex] = useState({});
    const [geoList, setGeoList] = useState(DefaultState);
    const [inputValue, setInputValue] = useState("");
    const [activeCity, setActiveCity] = useState([41.8781, -87.6298]);


    const fetchForecast = async(lat, lon) => {
        try {
            const res = await axios.get(`api/weather?lat=${lat}&lon=${lon}`)
            setForecast(res.data)
            
        } catch (error) {
            console.log("Error fetching forecast data:", error.message)
        }
    };
    const fetchAirPollution = async(lat, lon) => {
        try {
            const res = await axios.get(`api/pollution?lat=${lat}&lon=${lon}`)
            setAirPollution(res.data)
        } catch (error) {
            console.log("Error fetching air pollution data:", error.message)
        }
    };
    const fetchDailyForecast = async(lat, lon) => {
        try {
            const res = await axios.get(`api/dailyForecast?lat=${lat}&lon=${lon}`)
            setDailyForecast(res.data)
        } catch (error) {
            console.log("Error fetching air forcast data:", error.message)
        }
    };
    const fetchUVIndex = async(lat, lon) => {
        try {
            const res = await axios.get(`api/uvIndex?lat=${lat}&lon=${lon}`)
            setUvIndex(res.data)

        } catch (error) {
            console.log("Error fetching air UVI data:", error.message)
        }
    };
    const fetchGeoList = async (search) => {
        try {
            const res = await axios.get(`api/geoCoordinate?search=${search}`);
            setGeoList(res.data)

        } catch (error) {
            console.log("Error fetching data:", error.message)
        }
    };

    const handleInput = (e) => {
        setInputValue(e.target.value);

        if(e.target.value === ""){
            setGeoList(DefaultState);
        }
    };


    useEffect(() => {
        const debouncedFetch = debounce((search) => {
            fetchGeoList(search);
        }, 500)
        if(inputValue){
            debouncedFetch(inputValue)
        }
        return() => debouncedFetch.cancel();
    }, [inputValue])
 
    useEffect(() => {
        fetchForecast(activeCity[0], activeCity[1]);
        fetchAirPollution(activeCity[0], activeCity[1]);
        fetchDailyForecast(activeCity[0], activeCity[1]);
        fetchUVIndex(activeCity[0], activeCity[1]);
    }, [activeCity]);

    return(
        <GlobalContext.Provider value={{forecast, airPollution, dailyForecast, uvIndex, geoList, inputValue, handleInput,}}>
            <GlobalContextUpdate.Provider value={{setActiveCity}}>{children}</GlobalContextUpdate.Provider>
        </GlobalContext.Provider>
    )
};


export const useGlobalContext = () => useContext(GlobalContext);
export const useGlobalContextUpdate = () => useContext(GlobalContextUpdate);
