<script>
    import ErrorAlert from "../common/ErrorAlert.svelte";
    import SpinnerButton from "../common/SpinnerButton.svelte";
    import Avatar from "./Avatar.svelte";
    import {getContext} from "svelte";
    import SuccessAlert from "../common/SuccessAlert.svelte";

    const user = getContext("user");
    const channel = getContext("channel");
    let name = user.name;
    let email = user.email;
    let errorMessage = "";
    let successAlert;

    function saveName(e) {
        e.preventDefault();
        errorMessage = "";

        axios
            .post(channel.lucentUrl + "/account/update-name", {
                name: name,
            })
            .then((response) => {
                successAlert.show();
            })
            .catch((error) => {
                errorMessage = error.response?.data.error;
                console.log({errorMessage});
            });
    }

    function saveEmail(e) {
        e.preventDefault();
        errorMessage = "";

        axios
            .post(channel.lucentUrl + "/account/update-email", {
                email: email,
            })
            .then((response) => {
                successAlert.show();
            })
            .catch((error) => {
                errorMessage = error.response?.data.error;
                console.log({errorMessage});
            });
    }
</script>


<div class="wrapper-tiny">
    <ErrorAlert message={errorMessage}/>
    <SuccessAlert bind:this={successAlert} />
    <h3 class="header-small mb-5">
        <Avatar name={user.name}/>
    </h3>
    <form on:submit={saveName}>
        <div class="input-group mb-3">
            <input
                    type="text"
                    bind:value={name}
                    class="form-control"
                    placeholder="Name"
                    required
            />
            <SpinnerButton label="Update"/>
        </div>
    </form>

    <form on:submit={saveEmail}>
        <div class="input-group mb-3">
            <input
                    type="email"
                    bind:value={email}
                    class="form-control"
                    placeholder="Email"
                    required
            />
            <SpinnerButton label="Update"/>
        </div>
    </form>

    <div class="list-group">
        <a class="list-group-item list-group-item-action" href="{ channel.lucentUrl }/logout">Logout from this
            device</a>
    </div>
</div>
