<script lang="ts">
    import { onMount } from "svelte";
    import NavBarAutocompletable from "../Componentes/NavBarAutocompletable.svelte";
    import BarraHorizontalConTexto from "../Componentes/BarraHorizontalConTexto.svelte";
    import type { ClientePanel } from "../types";
    import { urlG } from "../stores/urlStore";
    import ModalEstatico from "../Componentes/ModalEstatico.svelte";

    let token: string = sessionStorage.getItem("token") || "";
    let user: ClientePanel | null = $state(null);
    let showmodal: boolean = $state(false);
    let showrecuperacionset: boolean = $state(false);
    let modaldata: string = $state("");

    onMount(async () => {
        fetchusuario();
    });
    async function fetchusuario() {
        try {
            let req = await fetch($urlG + "/api/usuario", {
                method: "GET",
                headers: {
                    Auth: token,
                },
            });
            if (!req.ok) {
                modaldata = (await req.json()).message;
                return;
            }
            user = await req.json();
        } catch {
            modaldata = "no se pudo hacer la request";
        }
    }

    async function submitpass(e: Event) {
        e.preventDefault();

        const target = e.target as HTMLFormElement;
        const passwordInput = target.querySelector(
            "#contraseña",
        ) as HTMLInputElement;
        const password = passwordInput.value;

        try {
            let req = await fetch($urlG + "/api/usuario", {
                method: "PATCH",
                headers: { Auth: token, "Content-Type": "application/json" },
                body: JSON.stringify({ contraseña: password }),
            });
            showmodal = false;

            modaldata = (await req.json()).message;
            return;
        } catch {
            modaldata = "no se pudo hacer la request";
        }
    }

    async function submitemail(e: Event) {
        e.preventDefault();

        const t = e.target as HTMLFormElement;
        const emailinput = t.querySelector(
            "#emailRecuperacion",
        ) as HTMLInputElement;
        const email: string = emailinput.value;

        try {
            let req = await fetch($urlG + "/api/usuario/emailrecuperacion", {
                method: "PUT",
                headers: { Auth: token, "Content-Type": "Application/json" },
                body: JSON.stringify({ EmailRecuperacion: email }),
            });
            showmodal = false;

            modaldata = (await req.json()).message;
            if (req.ok) {
                fetchusuario();
            }
            showrecuperacionset = false;
        } catch {
            modaldata = "no se pudo hacer la request";
            showrecuperacionset = false;
        }
    }
</script>

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

<NavBarAutocompletable />
<div class="mt-2">
    <BarraHorizontalConTexto text="Panel de Usuario" />
</div>
<div
    class="container d-flex justify-content-center align-items-center flex-column mt-2 mx-auto"
>
    <!-- Información del Usuario -->
    <div class="w-75 mb-4">
        <div class="card">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0">Información Personal</h5>
            </div>
            <div class="card-body">
                {#if !user}
                    <div class="d-flex justify-content-center my-5">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Cargando...</span>
                        </div>
                    </div>
                {:else}
                    <div class="mb-3">
                        <h6 class="text-muted fw-bold">DNI</h6>
                        <p class="lead">{user.dni}</p>
                    </div>
                    <div class="mb-3">
                        <h6 class="text-muted fw-bold">Nombre</h6>
                        <p class="lead">{user.nombre}</p>
                    </div>
                    <div class="mb-3">
                        <h6 class="text-muted fw-bold">Apellido</h6>
                        <p class="lead">{user.apellido}</p>
                    </div>
                    <div class="mb-3">
                        <h6 class="text-muted fw-bold">Domicilio</h6>
                        <p class="lead">{user.domicilio}</p>
                    </div>
                    <div class="mb-3">
                        <h6 class="text-muted fw-bold">Celular</h6>
                        <p class="lead">{user.celular}</p>
                    </div>
                    <div class="mb-3">
                        <h6 class="text-muted fw-bold">Correo Electrónico</h6>
                        <p class="lead">{user.email}</p>
                    </div>
                    <div class="mb-3">
                        <button
                            class="btn btn-primary"
                            onclick={() => (showmodal = true)}
                            >Cambiar Contraseña</button
                        >
                    </div>
                {/if}
            </div>
        </div>
    </div>
    <!-- Esto es un modal para el cambio de contraseña -->
    {#if showmodal}
        <div
            class="modal show d-block"
            tabindex="-1"
            style="background-color: rgba(0,0,0,0.3);"
        >
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Ingrese información</h5>
                        <button
                            type="button"
                            class="btn-close"
                            onclick={() => (showmodal = false)}
                            aria-label="Close"
                        ></button>
                    </div>
                    <form onsubmit={submitpass}>
                        <div class="modal-body">
                            <div class="mb-3">
                                <div class="mb-3 text-muted">
                                    <small
                                        >La contraseña debe tener al menos 8
                                        caracteres</small
                                    >
                                </div>
                                <label for="contraseña" class="form-label"
                                    >Contraseña</label
                                >
                                <input
                                    type="text"
                                    class="form-control"
                                    id="contraseña"
                                    placeholder="********"
                                />
                            </div>
                        </div>
                        <div
                            class="modal-footer d-flex justify-content-between"
                        >
                            <button
                                type="button"
                                class="btn btn-secondary"
                                onclick={() => (showmodal = false)}
                                >Cerrar</button
                            >
                            <button type="submit" class="btn btn-primary"
                                >Guardar cambios</button
                            >
                        </div>
                    </form>
                </div>
            </div>
        </div>
    {/if}

    <!-- Información de Correo de Recuperación -->
    <div class="w-75 mb-4">
        <div class="card">
            <div class="card-header bg-secondary text-white">
                <h5 class="mb-0">Correo de Recuperación</h5>
            </div>
            <div class="card-body">
                {#if !user}
                    <div class="d-flex justify-content-center my-5">
                        <div class="spinner-border text-info" role="status">
                            <span class="visually-hidden">Cargando...</span>
                        </div>
                    </div>
                {:else}
                    <div class="mb-3">
                        <h6 class="text-muted fw-bold">
                            Email de Recuperación
                        </h6>
                        <p class="lead">
                            {user.emailRecuperacion || "No configurado"}
                        </p>
                    </div>
                    <div class="mb-3">
                        <button
                            class="btn btn-secondary text-white"
                            onclick={() => (showrecuperacionset = true)}
                            >Actualizar Email de Recuperación</button
                        >
                    </div>
                    {#if showrecuperacionset}
                        <div
                            class="modal show d-block"
                            tabindex="-1"
                            style="background-color: rgba(0,0,0,0.3);"
                        >
                            <div class="modal-dialog">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h5 class="modal-title">
                                            Actualizar Email de Recuperación
                                        </h5>
                                        <button
                                            type="button"
                                            class="btn-close"
                                            onclick={() =>
                                                (showrecuperacionset = false)}
                                            aria-label="Close"
                                        ></button>
                                    </div>
                                    <form onsubmit={(e) => submitemail(e)}>
                                        <div class="modal-body">
                                            <div class="mb-3">
                                                <label
                                                    for="emailRecuperacion"
                                                    class="form-label"
                                                    >Email de Recuperación</label
                                                >
                                                <input
                                                    type="email"
                                                    class="form-control"
                                                    id="emailRecuperacion"
                                                    placeholder="correo@ejemplo.com"
                                                />
                                            </div>
                                        </div>
                                        <div
                                            class="modal-footer d-flex justify-content-between"
                                        >
                                            <button
                                                type="button"
                                                class="btn btn-secondary"
                                                onclick={() =>
                                                    (showrecuperacionset = false)}
                                                >Cancelar</button
                                            >
                                            <button
                                                type="submit"
                                                class="btn btn-primary"
                                                >Guardar</button
                                            >
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    {/if}
                {/if}
            </div>
        </div>
    </div>
</div>
