<script>
    import cookie from "js-cookie";
    import clsx from "clsx";
    import api from "$lib/axios";
    import { goto } from "$app/navigation";

    let form;
    let isLoadingOnSubmit = false;
    let showPassword = false;
    let alert = {
        success: true,
        message: "",
    };

    const togglePasswordVisibility = () => {
        showPassword = !showPassword;
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        isLoadingOnSubmit = true;
        try {
            const fd = new FormData(form);
            const response = await api.post("/account/register", Object.fromEntries(fd));
            const { meta, data } = response.data;

            form.reset();
            cookie.set("session", `Bearer ${meta.token}`);

            goto("/login");
        } catch (err) {
            alert.success = false;
            alert.message = err.message;
        } finally {
            isLoadingOnSubmit = false;
        }
    };
</script>

<div class="row g-0 flex-fill">
    <div class="col-12 col-lg-6 col-xl-8 d-none d-lg-block position-relative">
        <div
            class="bg-cover h-100 min-vh-100"
            style="background-image: url(https://images.unsplash.com/photo-1585421514738-01798e348b17?q=80&w=2940&auto=format&fit=crop&ixlib=rb-4.1.0&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D); background-size: cover;"
        ></div>
    </div>
    <div class="col-12 col-lg-6 col-xl-4 border-top-wide border-primary d-flex flex-column justify-content-center">
        <div class="container container-tight my-5 px-lg-5">
            <div class="text-center mb-4">
                <div class="navbar-brand navbar-brand-autodark" aria-label="Brand Logo">
                    <img src="/img/logo.png" alt="logo" class="navbar-brand-image" style="height: 5rem;" />
                </div>
            </div>
            <h2 class="h3 text-center mb-3">Buat akun baru anda</h2>
            {#if alert.message}
                <div class="alert alert-danger alert-dismissible" role="alert">
                    <div class="alert-icon">
                        <i class="ti ti-exclamation-circle"></i>
                    </div>
                    {alert.message}
                    <a href={"#"} class="btn-close" data-bs-dismiss="alert" aria-label="close"></a>
                </div>
            {/if}
            <form action="" method="POST" bind:this={form} onsubmit={handleSubmit} autocomplete="off" novalidate>
                <div class="mb-3">
                    <label for="username" class="form-label">Nama</label>
                    <input
                        id="username"
                        name="username"
                        type="text"
                        class={clsx("form-control", alert.message && (alert.success ? "is-valid" : "is-invalid"))}
                        placeholder="Nama anda"
                        autocomplete="off"
                        disabled={isLoadingOnSubmit}
                    />
                </div>

                <div class="mb-3">
                    <label for="email" class="form-label">Email</label>
                    <input
                        id="email"
                        name="email"
                        type="email"
                        class={clsx("form-control", alert.message && (alert.success ? "is-valid" : "is-invalid"))}
                        placeholder="nama@email.com"
                        autocomplete="off"
                        disabled={isLoadingOnSubmit}
                    />
                </div>

                <div class="mb-2">
                    <label for="password" class="form-label">Kata sandi</label>
                    <div class="input-group input-group-flat">
                        <input
                            id="password"
                            name="password"
                            type={showPassword ? "text" : "password"}
                            class={clsx("form-control", alert.message && (alert.success ? "is-valid" : "is-invalid"))}
                            placeholder="Kata sandi anda"
                            autocomplete="off"
                            disabled={isLoadingOnSubmit}
                        />
                        <span class="input-group-text">
                            <button
                                type="button"
                                class="link-secondary border-0 bg-transparent"
                                title={showPassword ? "Hide password" : "Show password"}
                                aria-label={showPassword ? "Hide Password" : "Show Password"}
                                onclick={togglePasswordVisibility}
                                disabled={isLoadingOnSubmit}
                            >
                                <i class="icon ti {showPassword ? 'ti-eye-off' : 'ti-eye'}"></i>
                            </button>
                        </span>
                    </div>
                </div>

                <div class="mb-2">
                    <label for="role" class="form-label">Daftar sebagai</label>
                    <select
                        id="role"
                        name="role"
                        class={clsx("form-select", alert.message && (alert.success ? "is-valid" : "is-invalid"))}
                        disabled={isLoadingOnSubmit}
                        required
                    >
                        <option value="" disabled selected>Pilih peran</option>
                        <option value="admin">Admin</option>
                        <option value="staff">Staff</option>
                    </select>
                </div>

                <div class="form-footer">
                    <button type="submit" class="btn btn-primary w-100" disabled={isLoadingOnSubmit}>
                        {#if isLoadingOnSubmit}
                            <span class="spinner-border spinner-border-sm" aria-hidden="true"></span>
                            <span class="visually-hidden" role="status">Loading...</span>
                        {:else}
                            <span>Daftar</span>
                        {/if}
                    </button>
                </div>
            </form>
            <div class="text-center text-secondary mt-4">
                Sudah mempunyai akun? <a href="/login">Masuk</a>
            </div>
        </div>
    </div>
</div>

<style>
    @media (min-width: 992px) {
        .bg-cover {
            position: fixed !important;
            top: 0 !important;
            left: 0 !important;
            width: 67.111111% !important;
            height: 100vh !important;
            z-index: 1;
        }
    }
</style>
