<script setup lang="ts">
import { AccountApiClient, type Account } from '@/api/account';
import AppButton from '@/components/AppButton.vue';
import AppPage from '@/components/AppPage.vue';
import PropertiesTable from '@/components/PropertiesTable.vue';
import { useProfileStore } from '@/stores/profile-store';
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 profileStore = useProfileStore()
const account: Ref<Account | null> = ref(null)

onMounted(async () => {
  if (!profileStore.state) {
    await router.replace('/')
    return
  }

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

async function deleteAccount() {
  if (!profileStore.state || !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(profileStore.state)
      await api.deleteAccount(account.value.id)
      await router.replace('/')
    } catch (err) {
      console.error(err)
    }
  }
}
</script>
<template>
  <AppPage :title="account?.name ?? ''">
    <PropertiesTable v-if="account">
      <tr>
        <th>ID</th>
        <td>{{ account.id }}</td>
      </tr>
      <tr>
        <th>Created at</th>
        <td>{{ new Date(account.createdAt).toLocaleString() }}</td>
      </tr>
      <tr>
        <th>Archived</th>
        <td>{{ account.archived }}</td>
      </tr>
      <tr>
        <th>Type</th>
        <td>{{ account.type }}</td>
      </tr>
      <tr>
        <th>Name</th>
        <td>{{ account.name }}</td>
      </tr>
      <tr>
        <th>Number Suffix</th>
        <td>{{ account.numberSuffix }}</td>
      </tr>
      <tr>
        <th>Currency</th>
        <td>{{ account.currency }}</td>
      </tr>
      <tr>
        <th>Description</th>
        <td>{{ account.description }}</td>
      </tr>
    </PropertiesTable>
    <div>
      <AppButton icon="wrench"
        @click="router.push(`/profiles/${profileStore.state?.name}/accounts/${account?.id}/edit`)">Edit</AppButton>
      <AppButton icon="trash" @click="deleteAccount()">Delete</AppButton>
    </div>
  </AppPage>
</template>
