<!-- pages/views in vue are basically root-level full-page components -->

<script setup lang="ts">

import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";

import { useItemsStore } from "../stores/ItemsStore.ts";
import type { Item } from "../models/Item.ts";

const store = useItemsStore();
const route = useRoute();
const router = useRouter();

const item = ref<Item>({
    id: 0,
    name: "",
    description: "",
    createdAt: "",
    lastEditedAt: ""
});

const id: string | undefined = route.params.id as string | undefined

onMounted(() => {
    if(id) {
        const existing = store.items.find(i => i.id == Number(id));
        if (existing) item.value = { ...existing };
    }
});

async function save(): Promise<void> {
    if(id) {
        await store.updateItem(Number(id), item.value);
    } else {
        await store.addItem(item.value);
    }

    router.push("/items"); // redirect
}

</script>

<template>

    <div>
        <h2>{{ id ? "Edit Item" : "Create Item" }}</h2> <!-- omg I love ternary operator :D -->

        <form @submit.prevent="save">
            <input v-model="item.name" placeholder="Name" />
            <input v-model="item.description" placeholder="Name" />
            <button type="submit">Save</button>
        </form>
    </div>

</template>