import React , {useState, useEffect} from 'react';

const get_taches = () => {
    return fetch("http://localhost:3001/tache")
    .then(response => {
        if (response.ok) {
            return response;
        } else {
            return response.text()
            .then((text) => {
                throw new Error(text);
            });
        }
    })
    .then(response => {
        return response.json();
    })
    .catch(err => {
        console.log(err.message);
        throw err;
    });
};

const add_tache = (tache) => {
    return fetch("http://localhost:3001/tache", 
    {
        method:"POST",
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(tache)
    })
    .then(response => {
        if (response.ok) {
            return response;
        } else {
            return response.text()
            .then((text) => {
                throw new Error(text);
            });
        }
    })
    .then(response => {
        return response.json();
    })
    .catch(err => {
        console.log(err.message);
        throw err;
    });
};

const remove_tache = (id) => {
    return fetch("http://localhost:3001/tache/" + id,
        {
            method: "DELETE"
        }
    )
    .then(response => {
        if (response.ok) {
            return response;
        } else {
            return response.text()
            .then((text) => {
                throw new Error(text);
            });
        }
    })
    .catch(err => {
        console.log(err.message);
        throw err;
    });
};

const AddTache = ({add_tache}) =>{
    const [intitule, setIntitule] = useState("");
    const [val, setVal] = useState(1);

    const handleSubmit = (e) => {
        e.preventDefault();
        add_tache({intitule: intitule, valeur: val});
        setIntitule("");
        setVal(1);
    }

    return <form onSubmit={handleSubmit}>
        <label htmlFor="intitule"> Intitule </label>
        <input type="text" value={intitule} onChange={(e) => {setIntitule(e.target.value)}}/>
        <br />
        <label htmlFor="val"> Valeur </label>
        <input type="Number" value={val} onChange={(e) => {setVal(e.target.value)}}/>
        <br />
        <button> Ajouter </button>
    </form>
}

const Taches = () => {
    const [taches, setTaches] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState();

    const handleAdding = (data) => {
        add_tache(data)
        .then(data => {
            setTaches(taches => [...taches, data]);
        });
    };
    
    const handleRemove = (id) => {
        remove_tache(id)
        .then(() => {
            setTaches(taches => taches.filter((p) => p.id !== id))
        });
    };

    useEffect(() => {
        get_taches()
        .then(data => {
            setTaches(data);
            setLoading(false);
        })
        .catch(e => {
            setError(e);
            setLoading(false);
        });
    }, []);

    return <div>
        <h1>Taches</h1>
        <AddTache add_tache={handleAdding}/>
        {
            loading ?
            'Chargement...' :
            error ?
            'Error d: ' + error :
            <ul>
                {taches.map(t => <li>
                    {t.intitule} {t.valeur} <button onClick={() => handleRemove(t.id)}>Supprimer</button>
                </li>)}
            </ul>
        }
    </div>
        
};

export default Taches;