<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";
    import axios from "axios";

    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;
            });
    }

    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;
            });
    }
</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-5">
            <input
                    type="text"
                    bind:value={name}
                    class="form-control mb-3"
                    placeholder="Name"
                    required
            />
            <SpinnerButton label="Update Name"/>
        </div>
    </form>

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