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

const route = useRoute()
const router = useRouter()

const addValueRecordModal = useTemplateRef('addValueRecordModal')
const history = useTemplateRef('history')
const account: Ref<Account | null> = ref(null)
const accountType = computed(() => {
  if (account.value === null) return null
  return AccountTypes.of(account.value.type)
})

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

async function deleteAccount() {
  if (!account.value) return
  if (
    await showConfirm(
      'Are you sure you want to delete this account? This will permanently remove the account and all associated transactions.',
    )
  ) {
    try {
      const api = new AccountApiClient(route)
      await api.deleteAccount(account.value.id)
      await router.replace(`/profiles/${getSelectedProfile(route)}`)
    } catch (err) {
      console.error(err)
    }
  }
}

async function addValueRecord() {
  const result = await addValueRecordModal.value?.show()
  if (result) {
    history.value?.reload()
  }
}

async function addCreditTransaction() {
  await router.push(
    `/profiles/${getSelectedProfile(route)}/add-transaction?credited-account=${account.value?.id}`,
  )
}
async function addDebitTransaction() {
  await router.push(
    `/profiles/${getSelectedProfile(route)}/add-transaction?debited-account=${account.value?.id}`,
  )
}
</script>
<template>
  <AppPage
    :title="account?.name ?? ''"
    v-if="account"
  >
    <div>
      <AppBadge
        size="lg"
        v-if="account.currentBalance !== null"
        class="font-mono"
      >
        {{ account.currency.code }} {{ formatMoney(account.currentBalance, account.currency) }}
      </AppBadge>
      <AppBadge
        size="lg"
        class="font-mono"
        >#{{ account.numberSuffix }}</AppBadge
      >
      <AppBadge
        size="lg"
        v-if="accountType"
        class="font-mono"
      >
        {{ accountType.emoji }} {{ accountType.name }}
      </AppBadge>
    </div>

    <p>{{ account.description }}</p>

    <PropertiesTable>
      <tr>
        <th>Created at</th>
        <td>{{ new Date(account.createdAt).toLocaleString() }}</td>
      </tr>
    </PropertiesTable>

    <ButtonBar>
      <AppButton
        @click="addValueRecord()"
        :disabled="account.archived"
        >Record Value</AppButton
      >
      <AppButton
        icon="wrench"
        :disabled="account.archived"
        @click="router.push(`/profiles/${getSelectedProfile(route)}/accounts/${account?.id}/edit`)"
      >
        Edit</AppButton
      >
      <AppButton
        icon="trash"
        @click="deleteAccount()"
        :disabled="account.archived"
        >Delete</AppButton
      >
    </ButtonBar>
    <ButtonBar>
      <AppButton
        @click="addCreditTransaction()"
        :disabled="account.archived"
        size="sm"
        icon="arrow-up-right-from-square"
        >Add Credit Transaction
      </AppButton>
      <AppButton
        @click="addDebitTransaction()"
        :disabled="account.archived"
        size="sm"
        icon="arrow-up-right-from-square"
        >Add Debit Transaction</AppButton
      >
    </ButtonBar>

    <AccountHistory
      :account="account"
      v-if="account"
      ref="history"
    />

    <AddValueRecordModal
      v-if="account"
      :account="account"
      ref="addValueRecordModal"
    />
  </AppPage>
</template>
