<script>
    import {
        CardHeader,
        CardTitle,
        Button,
        Card,
        Input,
        Form,
        CardBody,
        FormGroup,
        Modal,
    } from "@sveltestrap/sveltestrap";
    import { navigate } from "svelte-routing";
    import { urlG } from "../stores/urlStore";
    import ModalEstatico from "./ModalEstatico.svelte";
    import { parse } from "svelte/compiler";

    let email = $state("");
    let contraseña = $state("");
    let errorMessage = $state("");

    // @ts-ignore
    async function submitForm(event) {
        event.preventDefault();

        const data = { email, contraseña };
        try {
            const response = await fetch(String($urlG) + "/api/login", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify(data),
                credentials: "include",
            });

            if (!response.ok) {
                const errorData = await response.json();
                errorMessage = errorData.message;
                return;
            }

            const ret = await response.json();
            localStorage.setItem("email", ret.email);
            sessionStorage.setItem("token", ret.token);
            //setTimeout(() => console.log("50ms") ,50);
            navigate(ret.redirect);
        } catch (e) {}
    }

    let showrecuperarmodal = $state(false);
    let modaldata = $state("");

    let emailr = $state("");
    let emailrecovery = $state("");
    async function SubmitRecuperarContraseñaEmail(e) {
        e.preventDefault();
        if (emailrecovery == "") emailrecovery = emailr;

        try {
            const req = await fetch($urlG + "/api/recuperarUsuario", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                    Email: emailr,
                    EmailRecuperacion: emailrecovery,
                }),
            });
            const data = await req.json();
            showrecuperarmodal = false;
            if (req.ok) {
                showf2amodal = true;
                return;
            }

            //hago esto para que no puedan haber errores en caso de que intente recuperar 1 cuenta, aborte y intente recuperar una segunda
            emailr = "";
            emailrecovery = "";
            //
            modaldata = data.message;
        } catch {
            modaldata = "Fallo al hacer la request";
        }
    }

    let showf2amodal = $state(false);
    async function submitf2a(e) {
        e.preventDefault();

        const inputs = document.querySelectorAll(".otp-input");
        let otppin = "";

        inputs.forEach((x) => {
            otppin += x.value.trim();
        });
        if (otppin.length != 6) {
            modaldata = "la longitud del pin es incorrecta";
            return;
        }
        if (emailr == "") {
            modaldata = "Fallo vuelva a intentar";
            return;
        }
        try {
            const req = await fetch($urlG + "/api/ingresar2fa", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ Pin: otppin, Email: emailr }),
            });
            const data = await req.json();
            if (req.ok) {
                sessionStorage.setItem("token", data.token);
                localStorage.setItem("email", emailr);
                showf2amodal = false;
                navigate("/usuario");
            }
        } catch {
            modaldata = "Fallo al hacer la request";
        }
    }

    function handleInput(index) {
        const otpInputs = document.querySelectorAll(".otp-input");

        console.log(otpInputs);
        if (index === 5) return;

        otpInputs[index+1].focus();
    }

</script>

{#if modaldata}
    <ModalEstatico close={() => !!(modaldata = "")} payload={modaldata} />
{/if}

<Card
    class="position-sticky top-50 start-50 translate-middle-x border border-success"
    style="width: 20rem; height: auto;"
    theme="auto"
    outline
>
    <CardHeader>
        <CardTitle>Iniciar Sesión</CardTitle>
    </CardHeader>
    <CardBody>
        <Form onsubmit={(e) => submitForm(e)}>
            <FormGroup floating label="Email">
                <Input
                    type="email"
                    placeholder="ejemplo@mail.com"
                    bind:value={email}
                    required
                />
            </FormGroup>
            <FormGroup floating label="Contraseña">
                <Input
                    type="password"
                    placeholder="*********"
                    bind:value={contraseña}
                    required
                />
            </FormGroup>
            <FormGroup>
                <Button color="primary" type="submit">Ingresar</Button>
            </FormGroup>
        </Form>
        {#if errorMessage}
            <div
                class="alert alert-warning alert-dismissible fade show"
                role="alert"
            >
                <strong>{errorMessage}</strong>
                <button
                    type="button"
                    class="btn-close close"
                    aria-label="Close"
                    data-bs-dismiss="alert"
                ></button>
            </div>
        {/if}
        <hr />
            <button class="btn btn-link" onclick={() => {showrecuperarmodal = true; window.scrollTo(0,0);}}
            >Recuperar Cuenta</button
        >
    </CardBody>
</Card>
{#if showf2amodal}
    <div
        class="modal"
        tabindex="-1"
        style="display: block; background-color: rgba(0, 0, 0, 0.3);"
    >
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Recuperar Cuenta</h5>
                </div>
                <form onsubmit={submitf2a}>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="f2a" class="form-label">
                                Ingrese el codigo que tendria que haber llegado a su email
                            </label>
                            <div class="d-flex gap-2 justify-content-center">
                                {#each Array(6) as _, i}
                                    <input
                                        type="text"
                                        class="form-control text-center otp-input"
                                        maxlength="1"
                                        inputmode="numeric"
                                        pattern="[0-9]*"
                                        style="width: 3rem;"
                                        oninput={()=> handleInput(i)}
                                    />
                                {/each}
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer d-flex">
                        <button type="submit" class="btn btn-primary">
                            Enviar
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
{/if}

{#if showrecuperarmodal}
    <div
        class="modal"
        tabindex="-1"
        style="display: block; background-color: rgba(0, 0, 0, 0.3);"
    >
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Recuperar Cuenta</h5>
                    <button
                        type="button"
                        class="btn-close"
                        aria-label="Close"
                        onclick={() => (showrecuperarmodal = false)}
                    ></button>
                </div>
                <div class="modal-body">
                    <form onsubmit={SubmitRecuperarContraseñaEmail}>
                        <div class="mb-3">
                            <label for="Email" class="form-label">Email*</label>
                            <input
                                type="email"
                                class="form-control"
                                id="Email"
                                placeholder="Ingresa tu email"
                                required
                                bind:value={emailr}
                            />
                        </div>
                        <div class="mb-3">
                            <label for="recoveryEmail" class="form-label"
                                >Email Recuperacion</label
                            >
                            <input
                                type="email"
                                class="form-control"
                                id="recoveryEmail"
                                placeholder="Ingresa tu email de recuperacion"
                                bind:value={emailrecovery}
                            />
                        </div>
                        <div class="d-grid gap-2">
                            <button type="submit" class="btn btn-primary"
                                >Enviar</button
                            >
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
{/if}
