import { useEffect, useState } from 'react';
import { Activite, Session } from '../classes';
import { dateToString, hoursToString } from './edt';
import './style/edt.css';
import { Modal } from './Modal';
import Loading from './loading';
import {delay} from "../requetes";


type Props = {
    session:Session;
}

function EdtSession({session}:Props){

    const [open, setOpen] = useState<boolean>(false)
    const [loading,setLoading] = useState<boolean>(false);

    function handleOpen(): void {
        setOpen(!open);
    }

    function handleDeleteActivite(): void {
        session.activites.pop(); //TODO
    }

    function handleAddActivite(): void {
        const newActivite = new Activite();
        //TODO
        session.activites.push(newActivite);
    }

     async function updateActivites(){
        //TODO
        await delay(2000);
        //await updateActivitiesOfSessionAPI(session);
        setLoading(false);
    }


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

    const sDate = session.creneau;
    return(
        <div>
            <div className="edt_session" onClick={() => handleOpen()}>
                    <div className="edt_session_header">
                        <div className="edt_date">{hoursToString(sDate)}</div>
                        {session.isRecurrent && <div className="edt_date"> recurrent</div>}
                    </div>
                    <div>{session.name}</div>
            </div>
            {open && 
                <Modal isOpen={open} onClose={() => setOpen(false)}>
                    <div className="edt_session_modal">
                        <div>{session.name}</div>
                        <div>{hoursToString(sDate)}</div>
                        <div>{dateToString(sDate)}</div>
                        <div>
                            Activités :
                            <div className="ent_activite_list">
                                {session.activites.map((activite,index)=>(
                                    <div>
                                        {activite.nom}
                                        <button className="deleteButton" onClick={() => handleDeleteActivite}>x</button>
                                        </div>
                                ))}
                                <button  className="addButton" onClick={() => handleAddActivite}>+</button>
                                {loading && <div className='edt_loading'><Loading/></div>}
                            </div>
                        </div>
                    </div>
                </Modal>
            }
        </div>
    )
}

export default EdtSession
