<script lang="ts" setup>
import { computed, ref } from "vue";
import Autocomplete from '../components/Autocomplete.vue'
import { Transaction, useTransactionsStore } from "../stores/transactions";
import DateInput from "./DateInput.vue";
import Button from "./SimpleButton.vue";
import Input from "./Input.vue";

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

const TX = ref<Transaction>({
    Date: new Date(),
    Memo: "",
    Amount: 0,
    Payee: "",
    PayeeID: undefined,
    Category: "",
    CategoryID: undefined,
    CategoryGroup: "",
    GroupID: "",
    ID: "",
    Status: "Uncleared",
    TransferAccount: "",
    Reconciled: false
});

const payeeType = ref<string|undefined>(undefined);

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

const transactionsStore = useTransactionsStore();
function saveTransaction(e: MouseEvent) {
    e.preventDefault();
    Save();
}

function Save() {
    transactionsStore.saveTransaction(payload.value);
}

defineExpose({Save});
</script>

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