<script setup lang="ts">
import { AccountApiClient, type Account } from '@/api/account'
import AppButton from '@/components/AppButton.vue'
import HomeModule from '@/components/HomeModule.vue'
import { useProfileStore } from '@/stores/profile-store'
import { onMounted, ref, type Ref } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const profileStore = useProfileStore()

const accounts: Ref<Account[]> = ref([])

onMounted(async () => {
  if (!profileStore.state) {
    console.warn('No profile is selected.')
    return
  }

  const accountApi = new AccountApiClient(profileStore.state)
  accountApi.getAccounts().then(result => accounts.value = result)
    .catch(err => console.error(err))
})
</script>
<template>
  <HomeModule title="Accounts">
    <template v-slot:default>
      <table>
        <thead>
          <tr>
            <th>Name</th>
            <th>Currency</th>
            <th>Number</th>
            <th>Type</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="account in accounts" :key="account.id">
            <td>
              <RouterLink :to="`/profiles/${profileStore.state?.name}/accounts/${account.id}`">{{ account.name }}
              </RouterLink>
            </td>
            <td>{{ account.currency }}</td>
            <td>...{{ account.numberSuffix }}</td>
            <td>{{ account.type }}</td>
          </tr>
        </tbody>
      </table>
    </template>
    <template v-slot:actions>
      <AppButton icon="plus" @click="router.push(`/profiles/${profileStore.state?.name}/add-account`)">Add Account
      </AppButton>
    </template>
  </HomeModule>
</template>
<style lang="css"></style>
