<!--
  -   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);

    export let data: ExtendedEvent;
    let event = data.event;
    let name = event.name;
    let deadline = dayjs(event.deadline).utc(true).toISOString().slice(0, -1);
    let start = dayjs(event.start).utc(true).toISOString().slice(0, -1);
    let end = dayjs(event.end).utc(true).toISOString().slice(0, -1);
    let member = event.maxTeamMembers;
    let schemType = event.schemType;
    let publicOnly = event.publicSchemsOnly;
    let addReferee: {name: string, id: number}[] = [];
    let removeReferee: {name: string, id: number}[] = [];

    let errorOpen = false;
    let error: any = undefined;
    let deleteOpen = false;

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

    $: changed = 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 ||
        addReferee.length > 0 ||
        removeReferee.length > 0;


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

    let successToast: boolean = false;

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

        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" let:props size="lg">
            <input type="datetime-local" {...props} bind:value={deadline}/>
        </Input>
    </div>
    <div class="mt-4">
        <Label for="event-start">Start</Label>
        <Input id="event-start" bind:value={name} class="w-80" let:props size="lg">
            <input type="datetime-local" {...props} bind:value={start}/>
        </Input>
    </div>
    <div class="mt-4">
        <Label for="event-end">End</Label>
        <Input id="event-end" bind:value={name} class="w-80" let:props size="lg">
            <input type="datetime-local" {...props} bind:value={end}/>
        </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} on:click={update}>Update</Button>
        <Button class="ml-4" color="red" on:click={() => 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 on:click={() => deleteOpen = false}>Cancel</Button>
        <Button class="ml-4" color="red" on:click={del}>Delete</Button>
    </div>
</Modal>

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