<script setup lang="ts">
import { getSelectedProfile } from '@/api/profile'
import { TransactionApiClient, type TransactionVendor } from '@/api/transaction'
import AppButton from '@/components/common/AppButton.vue'
import AppPage from '@/components/common/AppPage.vue'
import ButtonBar from '@/components/common/ButtonBar.vue'
import EditVendorModal from '@/components/EditVendorModal.vue'
import VendorCard from '@/components/VendorCard.vue'
import { showConfirm } from '@/util/alert'
import { nextTick, onMounted, ref, useTemplateRef, type Ref } from 'vue'
import { useRoute } from 'vue-router'

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

const vendors: Ref<TransactionVendor[]> = ref([])
const editVendorModal = useTemplateRef('editVendorModal')
const editedVendor: Ref<TransactionVendor | undefined> = ref()

onMounted(async () => {
  await loadVendors()
})

async function loadVendors() {
  vendors.value = await transactionApi.getVendors()
}

async function addVendor() {
  editedVendor.value = undefined
  await nextTick()
  const result = await editVendorModal.value?.show()
  if (result === 'saved') {
    await loadVendors()
  }
}

async function editVendor(vendor: TransactionVendor) {
  editedVendor.value = vendor
  await nextTick()
  const result = await editVendorModal.value?.show()
  if (result === 'saved') {
    await loadVendors()
  }
}

async function deleteVendor(vendor: TransactionVendor) {
  const confirmed = await showConfirm(
    'Are you sure you want to delete this vendor? It will be permanently removed from all associated transactions.',
  )
  if (!confirmed) return
  await transactionApi.deleteVendor(vendor.id)
  await loadVendors()
}
</script>
<template>
  <AppPage title="Vendors">
    <p>
      Vendors are businesses and other entities with which you exchange money. Adding a vendor to
      Finnow allows you to track when you interact with that vendor on a transaction.
    </p>
    <VendorCard
      v-for="v in vendors"
      :key="v.id"
      :vendor="v"
      @edit="editVendor(v)"
      @delete="deleteVendor(v)"
    />
    <ButtonBar>
      <AppButton
        button-type="button"
        icon="plus"
        @click="addVendor()"
        >Add Vendor</AppButton
      >
    </ButtonBar>

    <EditVendorModal
      ref="editVendorModal"
      :vendor="editedVendor"
    />
  </AppPage>
</template>
