import React, {useState, useEffect} from 'react';
import { useParams } from 'react-router';
import {
    HashRouter as Router,
    Switch,
    Route,
    Link
  } from "react-router-dom";

const People = () => {
    const [people, setPeople] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState('');


    const get_people = () => {
        return fetch('http://localhost:8000/person')
        .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);
        });
        

    };

    const add_person = (nom, prenom) => {
        return fetch("http://localhost:8000/person", 
        {
            method:"POST",
            body: JSON.stringify({lastname: nom, firstname: prenom}),
            headers: {
                'Content-Type': 'application/json'
            }
        })
        .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);
        });
    }

    const remove_person = (id) => {
        return fetch("http://localhost:8000/person/"+id, 
        {
            method:"DELETE"
        })
        .then(response => {
            if (response.ok) {
                return response;
            } else {
                return response.text()
                .then((text) => {
                    throw new Error(text);
                });
            }
        })
        .then(response => {
            setPeople(people => people.filter((i) => i.id != id));
            return response.json();
        })
        .catch(err => {
            console.log(err.message);
        });
    }

    const get_mails = (id) => {
        return fetch('http://localhost:8000/person/'+id+'/mailAddress')
        .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);
        });
    }

    const get_phones = (id) => {
        return fetch('http://localhost:8000/person/'+id+'/phone')
        .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);
        });
    }   

    const Details = () => {
        const {id} = useParams();
        console.log("qs");
        const [phones, setPhones] = useState([]);
        const [mails, setMails] = useState([]);

        useEffect( () => {
            Promise.all([get_mails(id), get_phones(id)])
            .then(values => {
                setMails(values[0]);
                setPhones(values[1]);
            });
        },[id])
        return <>
    <h1> Courriels </h1>
        <ul>
        {
            mails.map(mail => 
                <li key={mail.id}>
                    {mail.address} ({mail.type})
                </li>
        )}
        </ul>
    <h1> Téléphones </h1>
        <ul>
        {
            phones.map(phone => 
                <li key={phone.id}>
                    {phone.number} ({phone.type})
                </li>
            
        )}
    </ul>
    </>
    };
        

    useEffect(() => {
        get_people()
        .then(data => {
            setPeople(data);
            setLoading(false);
        })
        .catch(err => {
            setError(err.message);
            setLoading(false);
        });
    }, []);

    const AddPeopleForm = ({add_person}) => {
        const [nom, setNom] = useState();
        const [prenom, setPrenom] = useState();

        const handleSubmit = (e) => {
            e.preventDefault();
            add_person(nom, prenom)
            .then(data => {
                setPeople( p => [... p, data]);
            }) .catch (e => {console.log(e.message)});
        }

        return (
            <form onSubmit={handleSubmit}>
                Prénom : <input type="text" value={prenom} onChange={e => setPrenom(e.target.value)}></input>
                Nom : <input type="text" value={nom} onChange={e => setNom(e.target.value)}></input>
                <button>Ajouter</button>
            </form>
        );
    }

    return <div>
        <h3>People</h3>
        <Route path="/people">
        <AddPeopleForm add_person={add_person}/>
        {
            loading ?
            'Chargement...' :
            error ?
            'Error d: ' + error :
            <ul>
                {people.map(p => <li>
                    {p.firstname} {p.lastname} <button onClick={() => remove_person(p.id)}>Supprimer</button> <Link to={`/people/${p.id}`}>Détails</Link>
                </li>)}
            </ul>
        }</Route>
        <Route path="/people/:id">
            <hr />
            <Link to ="/people">Close</Link>
            <Details />
        </Route>
    </div>;
};

export default People;