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

const userContext=createContext();

const SessionTime={
    "1200":["13:00", "14:00"],
    "1330":["14:20", "15:30"],
    "1500":["16:00", "17:00"],
    "1730":["18:30", "19:30"],
    "1900":["20:00", "21:00"],
    "2030":["21:30", "23: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);

    const refChoice=useRef();
    const refPassword=useRef();

    const {data}=useData();

  
    function getFileId(){
        if(!userId){
            if(data?.id){
                return `PC${data.id.toString().padStart(2,'0')}`;
            }
            return `${moment().format('hhmmss')}_testuser`;
        }return `${userId}`;
    }
    function getDataId(){
        if(!userId) return `${moment().format('YYYYMM')}/${moment().format("MMDD")}/${getSessionId()}/testuser_${moment().format('hhmmss')}`;
        return `${moment().format('YYYYMM')}/${moment().format("MMDD")}/${getSessionId()}/${userId}`;
    }

    function getUploadFolder(){
        return `${moment().format("YYYYMM")}/${moment().format("MMDD")}/${getSessionId()}`;
    }
    function setPassword(pass){
        refPassword.current=pass;
        console.log("Password changed:", pass);
    }
    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);
        // });
    }

    function writeSheet(){

        writeToGoogleSheet(
            moment().format("YYYY/MM/DD"),
            getSessionId(),
            userId,
            refPassword.current || '0000'
        ).then(() => {
            console.log("Data written to Google Sheet successfully");
        })
        .catch((error) => { 
            console.error("Error writing data to Google Sheet:", error);
        });
    }


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

        const data={
            userId,
            // sessionId,
            password: refPassword.current||'',
            choice: choice||'',
            summary: 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);
        // });

    },[choice, summary, refPassword.current]);
    
    function getSessionId(time){
        let symbol='no-session';
         for(const [key, value] of Object.entries(SessionTime)){
            const start=moment(value[0], "HH:mm");
            const end=moment(value[1], "HH:mm");

            if(time){
                const checkTime=moment(time, "HH:mm");
                if(checkTime.isBetween(start, end)){
                    return key;
                }
            }else{
                if(moment().isBetween(start, end)){
                    symbol=key;
                    break;
                }
            }
        }
        return symbol;
    }
    useEffect(() => {

  
        const symbol=getSessionId();
        setSessionId(symbol);
        

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

    }, [sessionId]);

    // console.log(getSessionId(), getSessionId("13:12"), getSessionId("14:55"), getSessionId("2213"));


    // useEffect(()=>{
    //     refChoice.current=choice;
    //     console.log("Choice changed:", choice);
    // }, [choice]);

    return (
        <userContext.Provider value={{ 
            userId, setUserId, getFileId, getUploadFolder,
            reset, uploadHistory: saveHistory, setChoice, 
            choice,
            setSummary, summary, getDataId,
            setPassword,
            writeSheet}}>
                {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 };