<script setup lang="ts">
import { ApiError } from '@/api/base';
import { formatMoney } from '@/api/data';
import { getSelectedProfile } from '@/api/profile';
import { TransactionApiClient, type TransactionDetail } from '@/api/transaction';
import AppButton from '@/components/AppButton.vue';
import AppPage from '@/components/AppPage.vue';
import CategoryLabel from '@/components/CategoryLabel.vue';
import PropertiesTable from '@/components/PropertiesTable.vue';
import TagLabel from '@/components/TagLabel.vue';
import { showAlert, showConfirm } from '@/util/alert';
import { onMounted, ref, type Ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const route = useRoute()
const router = useRouter()
const transactionApi = new TransactionApiClient(getSelectedProfile(route))

const transaction: Ref<TransactionDetail | undefined> = ref()

onMounted(async () => {
  const transactionId = parseInt(route.params.id as string)
  try {
    transaction.value = await transactionApi.getTransaction(transactionId)
  } catch (err) {
    console.error(err)
    await router.replace('/')
    if (err instanceof ApiError) {
      await showAlert('Failed to fetch transaction: ' + err.message)
    }
  }
})

async function deleteTransaction() {
  if (!transaction.value) return
  const conf = await showConfirm('Are you sure you want to delete this transaction? This will permanently delete all data pertaining to this transaction, and it cannot be recovered.')
  if (!conf) return
  try {
    await transactionApi.deleteTransaction(transaction.value.id)
    await router.replace(`/profiles/${getSelectedProfile(route)}`)
  } catch (err) {
    console.error(err)
  }
}
</script>
<template>
  <AppPage :title="'Transaction ' + transaction.id" v-if="transaction">
    <PropertiesTable>
      <tr>
        <th>Timestamp</th>
        <td>{{ new Date(transaction.timestamp).toLocaleString() }}</td>
      </tr>
      <tr>
        <th>Added at</th>
        <td>{{ new Date(transaction.addedAt).toLocaleString() }}</td>
      </tr>
      <tr>
        <th>Amount</th>
        <td>{{ formatMoney(transaction.amount, transaction.currency) }}</td>
      </tr>
      <tr>
        <th>Description</th>
        <td>{{ transaction.description }}</td>
      </tr>
      <tr v-if="transaction.vendor">
        <th>Vendor</th>
        <td>
          {{ transaction.vendor.name }}
        </td>
      </tr>
      <tr v-if="transaction.category">
        <th>Category</th>
        <td>
          <CategoryLabel :category="transaction.category" :clickable="true" />
        </td>
      </tr>
      <tr v-if="transaction.creditedAccount">
        <th>Credited Account</th>
        <td>
          {{ transaction.creditedAccount.name }}
        </td>
      </tr>
      <tr v-if="transaction.debitedAccount">
        <th>Debited Account</th>
        <td>
          {{ transaction.debitedAccount.name }}
        </td>
      </tr>
      <tr>
        <th>Tags</th>
        <td>
          <TagLabel v-for="t in transaction.tags" :key="t" :tag="t" />
        </td>
      </tr>
    </PropertiesTable>

    <div v-if="transaction.lineItems.length > 0">
      <h3>Line Items</h3>
      <table class="app-table">
        <thead>
          <tr>
            <th>#</th>
            <th>Amount per Item</th>
            <th>Quantity</th>
            <th>Description</th>
            <th>Category</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="i in transaction.lineItems" :key="i.idx">
            <td>{{ i.idx + 1 }}</td>
            <td>{{ formatMoney(i.valuePerItem, transaction.currency) }}</td>
            <td>{{ i.quantity }}</td>
            <td>{{ i.description }}</td>
            <td>{{ i.category?.name }}</td>
          </tr>
        </tbody>
      </table>
    </div>
    <div>
      <AppButton icon="wrench"
        @click="router.push(`/profiles/${getSelectedProfile(route)}/transactions/${transaction.id}/edit`)">
        Edit
      </AppButton>
      <AppButton icon="trash" @click="deleteTransaction()">Delete</AppButton>
    </div>
  </AppPage>
</template>
