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

const get_parts = () => {
    return fetch("http://localhost:3001/participant")
    .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_part = (part) => {
    return fetch("http://localhost:3001/participant", 
    {
        method:"POST",
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(part)
    })
    .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_part = (id) => {
    return fetch("http://localhost:3001/participant/" + 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 AddPart = ({add_part}) =>{
    const [nom, setNom] = useState("");
    const [prenom, setPrenom] = useState("");

    const handleSubmit = (e) => {
        e.preventDefault();
        add_part({nom: nom, prenom: prenom});
        setNom("");
        setPrenom("");
    }

    return <form onSubmit={handleSubmit}>
        <label htmlFor="prenom"> Prenom </label>
        <input type="text" value={prenom} onChange={(e) => {setPrenom(e.target.value)}}/>
        <br />
        <label htmlFor="nom"> Nom </label>
        <input type="text" value={nom} onChange={(e) => {setNom(e.target.value)}}/>
        <br />
        <button> Ajouter </button>
    </form>
}

const Participants = () => {
    const [participants, setParticipants] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState();

    const handleAdding = (data) => {
        add_part(data)
        .then(data => {
            setParticipants(participants => [...participants, data]);
        });
    };
    
    const handleRemove = (id) => {
        remove_part(id)
        .then(() => {
            setParticipants(participants => participants.filter((p) => p.id !== id))
        });
    };

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

    return <div>
        <h1>Participants</h1>
        <AddPart add_part={handleAdding}/>
        {
            loading ?
            'Chargement...' :
            error ?
            'Error d: ' + error :
            <ul>
                {participants.map(p => <li>
                    {p.prenom} {p.nom} <button onClick={() => handleRemove(p.id)}>Supprimer</button>
                </li>)}
            </ul>
        }
    </div>
        
};

export default Participants;