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

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

    const [showTodos, setShowTodos] = useState(false)
    const {loading, setLoading, errorCatch, errorLabel, axiosGet} = useAxiosTools(true)
    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 {
            const res = await axiosGet('api/todos/finished')
            setToDos(res.data)
        } catch (error) {
            errorCatch(error)
        } finally {
            setLoading(false)
        }
    }

    return <div>
        <button className="flex justify-between w-full bg-blue-700 px-2 py-1 rounded cursor-pointer"
                onClick={handleShow}>
            <h2 className="inline">Tâches terminées</h2>
            <span>Show</span>
        </button>

        {errorLabel()}
        {showTodos && <ul className="list-disc ml-5">
        {toDos.map(toDo => <li key={toDo.id}>{toDo.checked ? (new Date(toDo.checked)).toSmallFrDate() : ''} {toDo.name}</li>)}
        </ul>}
    </div>
}

export default ToDoFinish

interface ToDoFinishProps {
    reload: Date|null,
}
