import React, {FC, useEffect, useState} from "react"
import useAxiosTools from "../../hooks/AxiosTools"
import {toDo} from "../../utilities/types"
import {LoaderSVG, PlaySVG} from "../SVG"

const ToDoFinish: FC<ToDoFinishProps>  = ({reload}) => {

    const [showTodos, setShowTodos] = useState(false)
    const {loading, setLoading, errorCatch, errorLabel, axiosGet} = useAxiosTools()
    const [toDos, setToDos] = useState<toDo[]>([])

    useEffect(() => {
        if (showTodos) {
            setLoading(true)
            fetchFinishToDos()
        }
    }, [reload])

    const handleShow = () => {
        if (! showTodos) {
            setLoading(true)
            fetchFinishToDos()
        }
        setShowTodos(!showTodos)
    }

    const fetchFinishToDos = async () => {
        try {
            setLoading(true)
            const res = await axiosGet('api/todos/finished')
            setToDos(res.data)
        } catch (error) {
            errorCatch(error)
        } finally {
            setLoading(false)
        }
    }

    return <div>
        <button className="flex w-full cursor-pointer items-center justify-between rounded bg-blue-700 px-2 py-1"
                onClick={handleShow}>
            <h2 className="inline">
                Tâches terminées
                {loading && <LoaderSVG className="mb-px ml-2 inline h-5 stroke-white" />}
            </h2>

            <span><PlaySVG className={`w-4 transition ${showTodos ? 'rotate-90' : 'rotate-180'}`} /></span>
        </button>

        {errorLabel()}
        {showTodos && <ul className="m-2 list-disc">
            {toDos.length === 0 && <li className="flex">Aucun contenu a disponible</li>}
            {toDos.map(toDo => <li key={toDo.id} className="flex gap-2">
                <span>{toDo.checked ? (new Date(toDo.checked)).toSmallFrDate() : ''}</span>
                <span className="flex-1">{toDo.name}</span>
                <span>{toDo.duration.durationify()}</span>
            </li>)}
        </ul>}
    </div>
}

export default ToDoFinish

interface ToDoFinishProps {
    reload: Date|null,
}
