import React, {FormEvent, useState} from "react"
import useAuthUser from "../../hooks/AuthUser"
import PageLayout from "../../components/PageLayout"
import Card from "../../components/Card"
import Field from "../../components/Field"
import useAxiosTools from "../../hooks/AxiosTools"

const Profile = () => {

    const {authUser, setAuthUser, logout} = useAuthUser()
    const [latitude, setLatitude] = useState(0)
    const [longitude, setLongitude] = useState(0)
    const {errorCatch, axiosPost} = useAxiosTools()

    const submitLocation = async (event: FormEvent) => {
        event.preventDefault()

        try {
            const res = await axiosPost(`/api/locations`, {latitude, longitude})
            setAuthUser(res.data)
        } catch (error) {
            errorCatch(error)
        }
    }

    return <PageLayout>
        <div className="m-1 my-5 flex justify-between">
            <h1 className="text-lg font-bold">Profile de l&apos;utilisateur</h1>
            <div>
                <button type="button" onClick={logout} className="btn-primary text-lg font-bold">Se déconnecter</button>
            </div>
        </div>
        <Card className="mb-5">
            <div>Nom : <strong>{authUser?.name}</strong></div>
            <div>Email : <strong>{authUser?.email}</strong></div>
        </Card>
        {/*<div>Update name & email</div>*/}
        {/*<div>Change password</div>*/}
        {/*<div>Delete Account</div>*/}
        <Card>
            <h2>Météo</h2>

            {authUser?.locations && authUser.locations.length > 0 ? <>
                <h3>Emplacements</h3>
                <ul>
                    {authUser?.locations.map(location => <li key={location.id}>{location.latitude} - {location.longitude}</li>)}
                </ul>
            </> : <form onSubmit={submitLocation}>
                <h3>Ajouter un emplacement</h3>
                <div className="flex gap-2">
                    <Field name="latitude"
                           type="number"
                           step="0.0001"
                           value={latitude}
                           className="h-10"
                           onChange={event => setLatitude(Number(event.target.value))}>
                        Latitude
                    </Field>
                    <Field name="longitude"
                           type="number"
                           step="0.0001"
                           value={longitude}
                           className="h-10"
                           onChange={event => setLongitude(Number(event.target.value))}>
                        Longitude
                    </Field>
                    <div className="self-end">
                        <button type="submit" className="btn-primary h-10 w-24">Valider</button>
                    </div>
                </div>
            </form>}

        </Card>
    </PageLayout>
}

export default Profile
