<script lang="ts">
    import {Button, Input, Label, Modal} from "flowbite-svelte";
    import moment from "moment";
    import {createEventDispatcher} from "svelte";
    import ErrorModal from "../../components/ErrorModal.svelte";
    import {eventRepo} from "../../../repo/repo.js";
    import type {SWEvent} from "../../../types/event.js";

    export let open = false;
    const dispatch = createEventDispatcher();

    let errorOpen = false;
    let error = undefined;

    let eventName = "";
    let start = "";
    $: startDate = moment(start)
    let end = "";
    $: endDate = moment(end)

    $: canSubmit = eventName.length > 0 && startDate.isValid() && endDate.isValid() && startDate.isBefore(endDate)

    async function createEvent() {
        try {
            await $eventRepo.createEvent({
                name: eventName,
                start: startDate,
                end: endDate
            })
            dispatch("create");
            open = false;
        } catch (e) {
            error = e;
            errorOpen = true;
            open = false;
        }
    }

    function clear() {
        eventName = "";
        start = "";
        end = "";
    }
</script>

<Modal bind:open title="Create Event" outsideclose size="sm" on:hide={clear}>
    <div class="flex flex-col place-items-center text-center">
        <div class="w-2/3 m-2">
            <Label for="event-create-name">Event Name</Label>
            <Input id="event-create-name" bind:value={eventName} placeholder="Name..."></Input>
        </div>
        <div class="w-2/3 m-2">
            <Label for="event-create-start">End</Label>
            <Input id="event-create-start" bind:value={start} let:props>
                <input type="datetime-local" {...props} bind:value={start}/>
            </Input>
        </div>
        <div class="w-2/3 m-2">
            <Label for="event-create-start">End</Label>
            <Input id="event-create-start" bind:value={end} let:props>
                <input type="datetime-local" {...props} bind:value={end}/>
            </Input>
        </div>
    </div>
    <svelte:fragment slot="footer">
        <Button color="alternative" on:click={() => open = false} class="mr-auto">Cancel</Button>
        <Button on:click={createEvent} disabled={!canSubmit}>Create</Button>
    </svelte:fragment>
</Modal>

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