import { createContext, useState, useEffect, useContext, use } from "react";
import moment from "moment";
import { updateUser } from "./backend";

const userContext=createContext();

const SessionTime={
    A:["12:00", "13:30"],
    B:["13:30", "15:00"],
    C:["15:00", "17:30"],
    D:["17:30", "19:00"],
    E:["19:00", "20:30"],
    F:["20:30", "22:00"]
}


export function UserProvider({children}) {

    const [userId, setUserId] = useState(null);
    const [sessionId, setSessionId] = useState(null);
    const [password, setPassword] = useState(null);
    const [choice, setChoice] = useState(null);
    const [summary, setSummary] = useState(null);


    function getFileId(pass){
        if(!userId) return `${password||moment().format('hhmmss')}_testuser`;
        return `${password||pass||''}_${userId}`;
    }
    function getDataId(){
        if(!userId) return `${moment().format('YYYYMM')}/${moment().format("MMDD")}/${sessionId!=null? SessionTime[sessionId][0].replace(':',''):'no-session'}/testuser_${moment().format('hhmmss')}`;
        return `${moment().format('YYYYMM')}/${moment().format("MMDD")}/${sessionId!=null? SessionTime[sessionId][0].replace(':',''):'no-session'}/${userId}`;
    }

    function getUploadFolder(){
        return `${moment().format("YYYYMM")}/${moment().format("MMDD")}/${sessionId!=null? SessionTime[sessionId][0].replace(':',''):'no-session'}`;
    }

    function reset(){
        setUserId(null);
        setSessionId(null);
        setPassword(null);
        setChoice(null);
        setSummary(null);
    }

    function saveHistory(history) {
        console.log('Saving history:', history);

        const data={
            history,
        }
        updateUser('user/'+getDataId(), data)
        .then(() => {
            console.log("History saved successfully");
        })
        .catch((error) => { 
            console.error("Error saving history:", error);
        });
    }


    useEffect(()=>{
        console.log("User ID changed:", password, sessionId, userId);
        if(!userId) return;

        const data={
            userId,
            // sessionId,
            password,
            choice,
            summary,
            date: moment().format("YYYY-MM-DD hh:mm:ss"),
            fileId: getFileId(),
        };

        console.log("Updating user data:", data);

        updateUser('user/'+getDataId(), data)
        .then(() => {
            console.log("User data updated successfully");
        })
        .catch((error) => {
            console.error("Error updating user data:", error);
        });

    },[password, choice, summary]);

    useEffect(() => {

        let symbol='';

        for(const [key, value] of Object.entries(SessionTime)){
            const start=moment(value[0], "HH:mm");
            const end=moment(value[1], "HH:mm");

            if(moment().isBetween(start, end)){
                symbol=key;
                break;
            }
        }
        setSessionId(symbol);
        

    }, [userId]);
    useEffect(() => {
        console.log("Session ID changed:", sessionId);

    }, [sessionId]);

    return (
        <userContext.Provider value={{ 
            userId, setUserId, getFileId, getUploadFolder,
            reset, uploadHistory: saveHistory, setChoice,
            setSummary, summary, getDataId,
            setPassword}}>
                {children}
        </userContext.Provider>
    );
}


export function useUser() {
    const context = useContext(userContext);
    if (!context) {
        throw new Error("useUser must be used within a UserProvider");
    }
    return context;
}

export { userContext };