import React, {FC, useEffect, useState} from "react"
import {useParams} from "react-router-dom"
import useAxiosTools from "../../hooks/AxiosTools"
import {timeTracker, toDo} from "../../utilities/types"
import {EditSVG} from "../../components/SVG"
import Field, {TextArea} from "../../components/Field"
import TimeTrackerEdit from "../../components/TimeTrackers/TimeTrackerEdit"
import {Modal} from "../../components/Modals"

const ToDoShow = () => {

    const {id} = useParams()
    const {setLoading, errorCatch, errorLabel, axiosGet, axiosPut} = useAxiosTools(true)
    const [toDo, setToDo] = useState<toDo|null>(null)
    const [name, setName] = useState<string>('')
    const [description, setDescription] = useState<string>('')
    const [editMode, setEditMode] = useState(false)

    useEffect(() => {
        fetchToDo()
    }, [])

    const fetchToDo = async () => {
        try {
            const res = await axiosGet('/api/todos/' + id)
            setToDo(res.data)
        } catch (error) {
            errorCatch(error)
        } finally {
            setLoading(false)
        }
    }

    const handleEditTodoMode = async () => {
        if (editMode && toDo) {
            try {
                // @ts-expect-error remove checked for update item content
                delete toDo['checked']
                const res = await axiosPut('/api/todos/' + id, {...toDo, name, description})
                setToDo(res.data)
            } catch (error) {
                errorCatch(error)
            }
        } else {
            setName(toDo?.name ?? '')
            setDescription(toDo?.description ?? '')
        }
        setEditMode(!editMode)
    }

    return <div className="relative p-5">
        {errorLabel()}
        {editMode ? <>
            <button className="absolute right-5 flex" onClick={handleEditTodoMode}>Valider <EditSVG className="w-5"/></button>
            <Field name="name" value={name} onChange={event => setName(event.target.value)} />
            <TextArea name="description" value={description} onChange={event => setDescription(event.target.value)} />
        </> : <>
            <button className="absolute right-5" onClick={handleEditTodoMode}><EditSVG className="w-5"/></button>
            <h1 className="text-lg font-bold">{toDo?.name}</h1>
            <p>Terminé le {toDo?.checked ? (new Date(toDo.checked)).toSmallFrDate() : ''}</p>
            <p>{toDo?.description}</p>
        </>}


        {toDo && <ToDoTimeTrackers toDo={toDo}/>}
    </div>
}

export default ToDoShow

const ToDoTimeTrackers: FC<{toDo: toDo}> = ({toDo: toDo}) => {

    const {setLoading, errorCatch, errorLabel, axiosGet} = useAxiosTools(true)
    const [timeTrackers, setTimeTrackers] = useState<timeTracker[]>([])
    const [showTrackers, setShowTrackers] = useState<timeTracker|null>(null)
    const [reload, setReload] = useState<timeTracker|null>(null)

    useEffect(() => {
        fetchTimeTrackers()
    }, [])

    useEffect(() => {
        if (reload) {
            fetchTimeTrackers()
            setShowTrackers(null)
        }
    }, [reload])

    const fetchTimeTrackers = async () => {
        try {
            const res = await axiosGet(`/api/todos/${toDo.id}/time-trackers`)
            setTimeTrackers(res.data)
        } catch (error) {
            errorCatch(error)
        } finally {
            setLoading(false)
        }
    }

    const timeSpend = () => {
        let timer = 0
        let more = false
        timeTrackers.forEach(timeTracker => {
            if (! timeTracker.end_at) {
                more = true
            } else {
                timer += ((new Date(timeTracker.end_at)).getTime()) - (new Date(timeTracker.start_at)).getTime()
            }
        })

        timer = Math.floor(timer / 1000)
        return (more ? '+' : '') + timer.durationify()
    }

    return <div className="p-5">
        <div className="text-center">Temps passé : {timeSpend()}</div>
        {errorLabel()}
        <table className="mx-auto">
            <thead>
            <tr>
                <th>Début</th>
                <th>Fin</th>
                <th>Différence</th>
                <th />
            </tr>
            </thead>
            <tbody>
            {timeTrackers.map(timeTracker => <tr key={timeTracker.id} className="text-center">
                <td className="px-1">{timeTracker.start_at ? (new Date(timeTracker.start_at)).toSmallFrDate() : ''}</td>
                <td className="px-1">{timeTracker.end_at ? (new Date(timeTracker.end_at)).toSmallFrDate() : ''}</td>
                <td className="px-1 text-right">{timeTracker.start_at && timeTracker.end_at ? (new Date(timeTracker.end_at)).difference(new Date(timeTracker.start_at)) : ''}</td>
                <td className="px-1 text-right">
                    <button onClick={() => setShowTrackers(timeTracker)}>
                        <EditSVG className="w-5"/>
                    </button>
                </td>
            </tr>)}
            </tbody>
        </table>

        <Modal show={!!showTrackers} closeModal={() => setShowTrackers(null)}>
            {showTrackers && <TimeTrackerEdit timeTracker={showTrackers} setReload={setReload} />}
        </Modal>
    </div>
}
