import { useEffect, useState } from "react";
import { Activite, Athlete, Session } from "../../classes";
import { dateToString, hoursToString } from "../edt";
import { Modal } from "../Modal";
import CreateActivite from "../createActivite";
import Loading from "../loading";
import { addActiviteToSession, createActivityAPI, delay, deletActiviteFromSession, getSessionOfActivite, subscribeSessionAPI, unsubscribeSessionAPI } from "../../requetes";
import { useLocalData } from "../../context/useLocalData";

type Props = {
    session:Session;
    open:boolean;
    setOpen:(b:boolean)=>void
}

function DetailSession({session,open,setOpen}:Props){

    const {user,setUser} = useLocalData()

    const [activites,setActivites] = useState<Activite[]>([]);
    const [open2, setOpen2] = useState<boolean>(false);
    const [loading,setLoading] = useState<boolean>(false);
    const [join,setJoin] = useState<boolean>(user instanceof Athlete && user.sessions.includes(session));

    const sDate = session.creneau;

    function handleDeleteActivite(activite:Activite): void {
        session.activites.splice(session.activites.indexOf(activite), 1);
        deletActiviteFromSession(activite);
        setActivites([...session.activites])
    }

    function handleAddActivite(): void {
        setOpen2(true)
    }

    async function updateActivites(){
        const newActivites = await getSessionOfActivite(session);
        if(newActivites!=null){
            session.activites=newActivites;
        }
        setLoading(false);
    }


    useEffect(() => {
        if(open){
            setLoading(true);
            updateActivites()
        }
    },[open])

    async function subscribeSession(){
        if(user instanceof Athlete){
            await subscribeSessionAPI(user,session);
            user.sessions.push(session);
            setJoin(true);
        }
    }

    async function unsubscribeSession(){
        if(user instanceof Athlete){
            await unsubscribeSessionAPI(user,session);
            user.sessions = user.sessions.filter(s => s !== session);
            setJoin(false);
        }   
    }


    async function returnActivite(activite: Activite|null){
        if(activite!==null){
            activite.session = session;
            const newActivite = await createActivityAPI(activite);
            await addActiviteToSession(session,newActivite);
            if(newActivite!=null){
                session.activites.push(newActivite);
                setActivites([...session.activites])
            }

        }
        setOpen2(false);
    }

    useEffect(() => {
        if(!loading){
            setActivites([...session.activites])
        }
    },[loading])

    if(!open2){

        return(
            <Modal isOpen={open} onClose={() => setOpen(false)}>
                <div className="object_modal">
                    <h2>{session.name}</h2>
                    <div>{hoursToString(sDate)}</div>
                    <div>{dateToString(sDate)}</div>
                    {user instanceof Athlete  &&
                    <div>
                        {user.sessions.includes(session) ? <button onClick={()=>unsubscribeSession()}>quitter</button>
                        :<button onClick={()=>subscribeSession()}>rejoindre</button>}
                    </div>
                    }

                    <div>
                        Activités :
                        <div className="session_modal_activite_list">
                            {activites.map((activite,index)=>(
                                <div>
                                    {activite.nom}
                                    <button className="deleteButton" onClick={() => handleDeleteActivite(activite)}>x</button>
                                    </div>
                            ))}
                            <button  className="addButton" onClick={() => handleAddActivite()}>+</button>
                            {loading && <div className='top_left_loading'><Loading/></div>}
                        </div>
                        
                    </div>
                </div>
            </Modal>
        )
    }else{
        return(
        <CreateActivite returnActivite={(activite) => returnActivite(activite)} session={session}/>
        )
    }
}

export default DetailSession;
