<script lang="ts" setup>
import { computed, ref } from "vue";
import Autocomplete from './Autocomplete.vue'
import { useAccountStore } from '../stores/budget-account'
import DateInput from "./DateInput.vue";
import { useTransactionsStore } from "../stores/transactions";
import Input from "./Input.vue";
import Button from "./Button.vue";

const props = defineProps<{
    transactionid: string
}>()

const emit = defineEmits(["save"]);

const transactionsStore = useTransactionsStore();
const TX = transactionsStore.Transactions.get(props.transactionid)!;
const payeeType = ref<string|undefined>(undefined);

const payload = computed(() => JSON.stringify({
    date: TX.Date.toISOString().split("T")[0],
    payee: {
        Name: TX.Payee,
        ID: TX.PayeeID,
        Type: payeeType.value,
    },
    categoryId: TX.CategoryID,
    memo: TX.Memo,
    amount: TX.Amount.toString(),
    state: "Uncleared"
}));

function saveTransaction(e: MouseEvent) {
    e.preventDefault();
    transactionsStore.editTransaction(TX.ID, payload.value);
    emit('save');
}
</script>

<template>
    <tr>
        <td class="text-sm">
            <DateInput class="border-b-2 border-black" v-model="TX.Date" />
        </td>
        <td>
            <Autocomplete v-model:text="TX.Payee" v-model:id="TX.PayeeID" v-model:type="payeeType" model="payees" />
        </td>
        <td>
            <Autocomplete v-model:text="TX.Category" v-model:id="TX.CategoryID" model="categories" />
        </td>
        <td>
            <Input class="block w-full border-b-2 border-black" type="text" v-model="TX.Memo" />
        </td>
        <td class="text-right">
            <Input
                class="text-right block w-full border-b-2 border-black"
                type="currency"
                v-model="TX.Amount"
            />
        </td>
        <td>
            <Button class="bg-blue-500" @click="saveTransaction">Save</Button>
        </td>
        <td></td>
    </tr>
</template>