<script>
    import { goto } from "$app/navigation";
    import TimeAgo from "$lib/components/TimeAgo.svelte";
    import { error } from "@sveltejs/kit";

    export let data;
    const note = data.note;

    let formData = { title: note.title, content: note.content };

    async function changeNote() {
        const payload = {
            title: formData.title,
            content: formData.content,
        };

        const response = await fetch(
            `http://no08g0o48sc8w0woowwsskos.134.255.231.190.sslip.io/api//note/${note.id}`,
            {
                method: "PUT",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify(payload),
            },
        );
        console.log(response.status);
        if (response.ok) {
            goto("/");
        } else {
            error(500, "Bad Request");
        }
    }

    async function deleteNote() {
        const response = await fetch(
            `http://no08g0o48sc8w0woowwsskos.134.255.231.190.sslip.io/api/note/${note.id}`,
            {
                method: "DELETE",
                headers: {
                    "Content-Type": "application/json",
                },
            },
        );

        if (response.ok) {
            goto("/");
        } else {
            error(500, "Bad Request");
        }
    }
</script>

<div class="container">
    <h1 class="title">Ändere Notiz: {note.title}</h1>

    <form on:submit|preventDefault={changeNote}>
        <fieldset>
            <label>
                Titel
                <input
                    name="title"
                    placeholder="Titel"
                    bind:value={formData.title}
                />
            </label>
            <label>
                Inhalt
                <textarea
                    name="content"
                    placeholder="Inhalt"
                    bind:value={formData.content}
                >
                </textarea>
            </label>
        </fieldset>

        <input type="submit" value="Ändern" />
    </form>

    <div class="button-container">
        <button class="secondary" on:click={deleteNote}>Notiz Löschen</button>
    </div>
    <br />
    <TimeAgo timestamp={note.createdOn}></TimeAgo>
</div>

<style>
    .button-container {
        display: flex;
        justify-content: center; /* Centers the button horizontally */
        margin-top: 1rem;
    }

    button {
        width: 100%;
        background-color: rgb(194, 43, 43);
        border-color: rgba(255, 255, 255, 0);
    }
</style>
