<script lang="ts">

    import {Button, Modal, Navbar, NavBrand, NavHamburger, NavLi, NavUl, Spinner} from "flowbite-svelte";
    import {replace} from "svelte-spa-router";
    import {PlusSolid} from "flowbite-svelte-icons";
    import EventCard from "./home/EventCard.svelte";
    import CreateEventModal from "./home/CreateEventModal.svelte";
    import {eventRepo, tokenStore} from "../../repo/repo.js";

    let events = $eventRepo.listEvents()
    let showAdd = false
    let showLogoutModal = false
    let millis = Date.now()

    function logout() {
        $tokenStore = ""
        replace("/login")
    }
</script>

<Navbar let:hidden let:toggle class="shadow-lg border-b">
    <NavBrand href="#">
        <span class="self-center whitespace-nowrap text-xl font-semibold dark:text-white">
          Admin-Tool
        </span>
    </NavBrand>
    <NavHamburger on:click={toggle} />
    <NavUl {hidden}>
        <NavLi href="#/edit">Edit Pages</NavLi>
        <NavLi href="#/perms">Permissions</NavLi>
        <NavLi on:click={() => showLogoutModal = true} class="cursor-pointer select-none">Logout</NavLi>
    </NavUl>
</Navbar>

<CreateEventModal bind:open={showAdd} on:create={() => events = $eventRepo.listEvents()}/>

<Modal bind:open={showLogoutModal} title="Logout?" outsideclose size="sm">
    <p>Do you really want to logout?</p>
    <svelte:fragment slot="footer">
        <Button on:click={() => showLogoutModal = false} color="alternative" class="ml-auto">Cancel</Button>
        <Button on:click={logout} color="red">Logout</Button>
    </svelte:fragment>
</Modal>

{#await events}
    <div class="h-screen w-screen grid place-items-center">
        <Spinner size={16}/>
    </div>
{:then data}
    <Button class="fixed bottom-6 right-6 !p-4 z-10 shadow-lg" on:click={() => showAdd = true}>
        <PlusSolid/>
    </Button>

    <h1 class="text-3xl mt-4 ml-4">Upcoming</h1>
    <div class="grid gap-4 p-4 border-b" style="grid-template-columns: repeat(auto-fill, minmax(300px, 1fr))">
        {#each data.filter((e) => e.start > millis) as event}
            <EventCard {event} />
        {/each}
    </div>
    <h1 class="text-3xl mt-4 ml-4">Past</h1>
    <div class="grid gap-4 p-4" style="grid-template-columns: repeat(auto-fill, minmax(300px, 1fr))">
        {#each data.filter((e) => e.start < millis).reverse() as event}
            <EventCard {event} />
        {/each}
    </div>
{:catch error}
    <p>
        {error.message}
    </p>
{/await}

<svelte:head>
    <title>SteamWar.de Multitool - Home</title>
</svelte:head>
