<script setup lang="ts">
import { AccountApiClient, type AccountValueRecord } from '@/api/account'
import { formatMoney } from '@/api/data'
import { getSelectedProfile } from '@/api/profile'
import AppBadge from '@/components/common/AppBadge.vue'
import AppButton from '@/components/common/AppButton.vue'
import AppPage from '@/components/common/AppPage.vue'
import AttachmentRow from '@/components/common/AttachmentRow.vue'
import ButtonBar from '@/components/common/ButtonBar.vue'
import PropertiesTable from '@/components/PropertiesTable.vue'
import { showConfirm } from '@/util/alert'
import { onMounted, ref, type Ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()
const valueRecord: Ref<AccountValueRecord | null> = ref(null)

onMounted(async () => {
  const accountId = parseInt(route.params.accountId as string)
  const id = parseInt(route.params.valueRecordId as string)
  try {
    const api = new AccountApiClient(route)
    valueRecord.value = await api.getValueRecord(accountId, id)
  } catch (err) {
    console.error(err)
    await router.replace('/')
  }
})

async function deleteValueRecord() {
  if (!valueRecord.value) return
  const confirm = await showConfirm(
    "Are you sure you want to delete this value record? This may affect how your account's balance is calculated.",
  )
  if (!confirm) return
  const api = new AccountApiClient(route)
  try {
    await api.deleteValueRecord(valueRecord.value.accountId, valueRecord.value.id)
    await router.replace(
      `/profiles/${getSelectedProfile(route)}/accounts/${valueRecord.value.accountId}`,
    )
  } catch (err) {
    console.error(err)
  }
}
</script>
<template>
  <AppPage
    title="Value Record"
    v-if="valueRecord"
  >
    <PropertiesTable>
      <tr>
        <th>ID</th>
        <td>{{ valueRecord.id }}</td>
      </tr>
      <tr>
        <th>Value</th>
        <td>
          <AppBadge>{{ formatMoney(valueRecord.value, valueRecord.currency) }}</AppBadge>
        </td>
      </tr>
    </PropertiesTable>
    <div v-if="valueRecord.attachments.length > 0">
      <h3>Attachments</h3>
      <AttachmentRow
        v-for="a in valueRecord.attachments"
        :attachment="a"
        :key="a.id"
        disabled
      />
    </div>
    <ButtonBar>
      <AppButton
        type="button"
        icon="trash"
        size="sm"
        @click="deleteValueRecord()"
      >
        Delete this record
      </AppButton>
    </ButtonBar>
  </AppPage>
</template>
