<script lang="ts">
    import {
        Navbar,
        NavbarBrand,
        NavbarToggler,
        Nav,
        Collapse,
        Button,
    } from "@sveltestrap/sveltestrap";
    import { onMount } from "svelte";
    import { writable } from "svelte/store";
    import { link, links } from "svelte-routing";
    import "./css/popup.css";
    import type { Grupo } from "../types";

    import { urlG } from "../stores/urlStore";
    import { navigate } from "svelte-routing";

    let isOpen: boolean = $state(false);
    let hayNotis: boolean = $state(false);

    const permisos = writable<Grupo[]>([]);
    const email = localStorage.getItem("email");
    const token = sessionStorage.getItem("token");

    async function obtenerPermisos() {
        try {
            const response = await fetch(String($urlG) + "/api/acciones", {
                method: "GET",
                headers: {
                    Auth: String(token),
                    Email: String(email),
                    "Content-Type": "application/json",
                },
            });
            if (response.ok) {
                const json = await response.json();

                permisos.set(json);
            }
        } catch (e) {
            console.error(e);
        }
    }

    onMount(() => {
        obtenerPermisos();
        obtenerNotis();
    });

    async function obtenerNotis() {
        try {
            const responce = await fetch(
                $urlG + "/api/notificaciones/haySinLeer",
                {
                    method: "GET",
                    headers: {
                        Auth: String(token),
                    },
                },
            );
            if (responce.ok) {
                let data = await responce.json();
                hayNotis = data.message;
                return;
            }
        } catch (e) {
            console.error(e);
        }
    }

    function redirijir(path: string) {
        navigate(path);
    }

    let theme = $state(localStorage.getItem("theme") ?? "light");
    const toggleTheme = () => {
        theme = theme === "light" ? "dark" : "light";
        document.body.setAttribute("data-bs-theme", theme);
        localStorage.setItem("theme", theme);
    };

    async function cerrarSesion() {
        try{
            const req = await fetch($urlG+"/api/logout", {
                method: "DELETE",
                headers: {
                    "Auth": token || "",
                }
            });

        }finally{
            localStorage.removeItem("email");
            sessionStorage.removeItem("token");
            navigate("/");
        }
    }
</script>

<Navbar class="border-bottom" container="xxl" expand="md" color="dark-subtle">
    <NavbarBrand href="/">AlquilaFacil</NavbarBrand>
    <div class="d-flex gap-2">
        <div class="badge" style="background-color: turquoise;" use:links>
            <a href="/Menu">
                <img src="/home.svg" alt="Volver al Menú" />
            </a>
        </div>
        <button
            class="badge btn"
            onclick={toggleTheme}
            style="background-color: cadetblue;"
        >
            {#if theme === "light"}
                <img src="/toggle-left.svg" alt="" />
            {:else}
                <img src="/toggle-right.svg" alt="" />
            {/if}
        </button>
        <button
            class="badge btn btn-info position-relative"
            onclick={() => navigate("/notificaciones")}
        >
            <img src="/bell.svg" alt="" />
            {#if hayNotis}
                <span
                    class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger"
                >
                    !
                    <span class="visually-hidden">unread messages</span>
                </span>
            {/if}
        </button>
        <button
            class="btn badge"
            onclick={() => navigate("/usuario")}
            style="background-color: wheat;"
        >
            <img src="/user.svg" alt="usuario" />
        </button>
        <div class="vr"></div>
        <button class="badge btn btn-danger" onclick={cerrarSesion}>
            <img src="/logout.svg" alt="CerrarSesion" />
        </button>
    </div>

    <NavbarToggler on:click={() => (isOpen = !isOpen)} />
    <Collapse {isOpen} navbar expand="md">
        <Nav class="ms-auto" navbar>
            {#each $permisos as item}
                <div class="dropdown">
                    <div
                        class="btn-group"
                        style="margin-left: 3px; margin-top: 3px"
                    >
                        <button
                            class="btn btn-secondary"
                            onclick={() => redirijir("/grupo/" + item.nombre)}
                            >{item.nombre}</button
                        >
                        <button
                            class="btn btn-secondary dropdown-toggle dropdown-toggle-split"
                            type="button"
                            data-bs-toggle="dropdown"
                            aria-expanded="false"
                        >
                            <span class="visually-hidden">Toggle Dropdown</span>
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end" use:links>
                            {#each item.idpermisos as perm}
                                <a
                                    class="dropdown-item link-underline-opacity-0 link-underline"
                                    href="/accion/{perm.id}"
                                    >{perm.descripcion}</a
                                >
                                <li><hr class="dropdown-divider" /></li>
                            {/each}
                        </ul>
                    </div>
                </div>
            {/each}
        </Nav>
    </Collapse>
</Navbar>
