<script setup lang="ts">
import { useShoppingListStore } from '../store/shoppingList';
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';

const store = useShoppingListStore();
const router = useRouter();

const isValid = ref(false);
const item = reactive({
  name: '',
  price: 0.99,
  user: '',
  description: '',
});

const form = ref(null);

const submit = () => {
  if (isValid.value === false) return;
  store.items.push({
    name: item.name,
    price: item.price * 100,
    user: store.users.find(user => user.name === item.user),
    description: item.description,
  });
  router.push('/shopping-list');
};
</script>

<template>
  <v-form ref="form" v-model="isValid" lazy-validation>
    <v-text-field
      label="Item Name"
      required
      v-model="item.name"
      validate-on="blur"
      :rules="[v => !!v || 'Item is required']"
    />
    <v-text-field
      label="Price"
      suffix="€"
      required
      v-model="item.price"
      validate-on="blur"
      :rules="[v => !!v || 'Item is required']"
    />
    <v-text-field
      label="Description"
      required
      v-model="item.description"
      validate-on="blur"
      :rules="[v => !!v || 'Item is required']"
    />
    <v-select
      label="User"
      :items="store.users.map(user => user.name)"
      required
      v-model="item.user"
      validate-on="blur"
      :rules="[v => !!v || 'Item is required']"
    />
    <v-btn color="primary" @click="submit()">add item</v-btn>
  </v-form>
</template>
