<script>
    import ErrorAlert from "../common/ErrorAlert.svelte";
    import SpinnerButton from "../common/SpinnerButton.svelte";

    import Nav from "./Nav.svelte";

    let name = "";
    export let userCount = 1;
    export let email = "";
    export let token = "";
    let password = "";
    let errorMessage = "";

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

        axios
            .post("/register", {
                name: name,
                password: password,
                email: email,
                token: token,
                isAdmin: userCount === 0,
            })
            .then(() => {
                window.location = "/login";
            })
            .catch((error) => {
                errorMessage = error.response?.data.error;
                console.log({errorMessage});
            });
    }
</script>

<Nav active="Register"/>
<div class="wrapper-tiny">
    {#if token || userCount === 0}
        <ErrorAlert message={errorMessage}/>

        <form on:submit={register}>
            <div class="mb-3">
                <label for="name" class="form-label">Name</label>
                <input
                    type="text"
                    bind:value={name}
                    class="form-control"
                    id="name"
                />
            </div>
            <div class="mb-3">
                <label for="email" class="form-label">Email address</label>
                <input
                    type="email"
                    bind:value={email}
                    class="form-control"
                    id="email"
                    disabled={userCount !== 0}
                />
            </div>
            <div class="mb-3">
                <label for="password" class="form-label">Password</label>
                <input
                    type="password"
                    bind:value={password}
                    class="form-control"
                    id="password"
                />
            </div>
            <div class="mb-3 form-check">
                <input
                    type="checkbox"
                    class="form-check-input"
                    id="terms"
                    required
                />
                <label class="form-check-label" for="terms"
                >I Agree to the <a
                    href="https://www.radical-elements.com/terms-of-service"
                    target="_blank">terms and conditions</a
                ></label
                >
            </div>

            <div class="text-center mt-5 d-block">
                <SpinnerButton label="Register"/>
            </div>
        </form>
    {:else}
        <p class="text-center mb-0">Registrations are currently closed</p>
    {/if}
</div>
