<!--
  -   This file is a part of the SteamWar software.
  -
  -   Copyright (C) 2023 SteamWar.de-Serverteam
  -
  -   This program is free software: you can redistribute it and/or modify
  -   it under the terms of the GNU Affero General Public License as published by
  -   the Free Software Foundation, either version 3 of the License, or
  -   (at your option) any later version.
  -
  -   This program is distributed in the hope that it will be useful,
  -   but WITHOUT ANY WARRANTY; without even the implied warranty of
  -   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  -   GNU Affero General Public License for more details.
  -
  -   You should have received a copy of the GNU Affero General Public License
  -   along with this program.  If not, see <https://www.gnu.org/licenses/>.
  -->

<script lang="ts">
    import type {ExtendedEvent} from "@type/event.ts";
    import {Button, Input, Label, Modal, Range, Select, Toast, Toggle} from "flowbite-svelte";
    import {schemTypes} from "@stores/stores.ts";
    import dayjs from "dayjs";
    import utc from "dayjs/plugin/utc";
    import {eventRepo, type UpdateEvent} from "@repo/event.ts";
    import ErrorModal from "../../components/ErrorModal.svelte";
    import {replace} from "svelte-spa-router";
    import {CheckCircleOutline} from "flowbite-svelte-icons";

    dayjs.extend(utc);

  interface Props {
    data: ExtendedEvent;
  }

  let { data }: Props = $props();
    let event = $state(data.event);
    let name = $state(event.name);
    let deadline = $state(dayjs(event.deadline).utc(true).toISOString().slice(0, -1));
    let start = $state(dayjs(event.start).utc(true).toISOString().slice(0, -1));
    let end = $state(dayjs(event.end).utc(true).toISOString().slice(0, -1));
    let member = $state(event.maxTeamMembers);
    let schemType = $state(event.schemType);
    let publicOnly = $state(event.publicSchemsOnly);

    let errorOpen = $state(false);
    let error: any = $state(undefined);
    let deleteOpen = $state(false);

    let deadlineDate = $derived(dayjs(deadline));
    let startDate = $derived(dayjs(start));
    let endDate = $derived(dayjs(end));
    let selectTypes = $derived([{
        value: null,
        name: "None"
    }, ...$schemTypes.map((type) => {
        return {
            value: type.db,
            name: type.name
        };
    })]);

    let changed = $derived(name !== event.name ||
        deadlineDate.diff(dayjs(event.deadline)) !== 0 ||
        startDate.diff(dayjs(event.start)) !== 0 ||
        endDate.diff(dayjs(event.end)) !== 0 ||
        member !== event.maxTeamMembers ||
        schemType != event.schemType ||
        publicOnly !== event.publicSchemsOnly);


    async function del() {
        try {
            await $eventRepo.deleteEvent(event.id.toString());
            await replace("/");
        } catch (e) {
            error = e;
            errorOpen = true;
        }
    }

    let successToast: boolean = $state(false);

    async function update() {
        let ev: UpdateEvent = {
            deadline: deadlineDate,
            end: endDate,
            maxTeamMembers: member,
            name: name,
            publicSchemsOnly: publicOnly,
            schemType: schemType ?? "null",
            start: startDate,
            addReferee: [],
            removeReferee: []
        };

        try {
            event = await $eventRepo.updateEvent(event.id.toString(), ev);
            successToast = true;
            setTimeout(() => successToast = false, 5000);
        } catch (e) {
            error = e;
            errorOpen = true;
        }
    }
</script>

<svelte:head>
    <title>{event.name} - Edit</title>
</svelte:head>

<form class="m-4">
    <div class="mt-4">
        <Label for="event-name">Name</Label>
        <Input type="text" id="event-name" bind:value={name} class="w-80" size="lg"></Input>
    </div>
    <div class="mt-4">
        <Label for="event-deadline">Deadline</Label>
        <Input id="event-deadline" bind:value={name} class="w-80"  size="lg">
            {#snippet children({ props })}
            <input type="datetime-local" {...props} bind:value={deadline}/>
                    {/snippet}
        </Input>
    </div>
    <div class="mt-4">
        <Label for="event-start">Start</Label>
        <Input id="event-start" bind:value={name} class="w-80"  size="lg">
            {#snippet children({ props })}
            <input type="datetime-local" {...props} bind:value={start}/>
                    {/snippet}
        </Input>
    </div>
    <div class="mt-4">
        <Label for="event-end">End</Label>
        <Input id="event-end" bind:value={name} class="w-80"  size="lg">
            {#snippet children({ props })}
            <input type="datetime-local" {...props} bind:value={end}/>
                    {/snippet}
        </Input>
    </div>
    <div class="mt-4">
        <Label for="event-member">Member: {member}</Label>
        <Range id="event-member" bind:value={member} step="1" min="1" max="30"/>
    </div>
    <div class="mt-4">
        <Label for="event-type">Schematic Type:</Label>
        <Select bind:value={schemType} items={selectTypes}/>
    </div>
    <Toggle bind:checked={publicOnly} class="mt-4">Public Schematics Only</Toggle>
    <div class="flex mt-4">
        <Button disabled={!changed} onclick={update}>Update</Button>
        <Button class="ml-4" color="red" onclick={() => deleteOpen = true}>Delete</Button>
    </div>
</form>

<ErrorModal bind:open={errorOpen} bind:error={error}/>

<Modal bind:open={deleteOpen} outsideclose title="Delete {event.name}?">
    <p>Are you sure you want to delete {event.name}?</p>
    <div class="flex justify-end">
        <Button onclick={() => deleteOpen = false}>Cancel</Button>
        <Button class="ml-4" color="red" onclick={del}>Delete</Button>
    </div>
</Modal>

<Toast bind:open={successToast} position="bottom-left" color="green">
    {#snippet icon()}
    <CheckCircleOutline />
  {/snippet}
    Updated Successfully
</Toast>
