<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from "vue-router"
import { useToast } from 'vue-toast-notification'
import axios from 'axios'

import Invoice from "./../classes/invoice"
import { calculateArr } from "./../classes/invoice_item"

import invoiceHeader from './../components/invoice_header.vue'
import itemSelector from './../components/item_selector.vue'
import invoiceItemsTable from './../components/invoice_items_table.vue'
import invoiceSummary from './../components/invoice_summary.vue'

const toast = useToast({
  position: 'top-right'
})

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

const invoiceId = route.params.id
const invoice = ref(new Invoice())
const items = ref<any[]>([])

const invoiceIsLoading = ref(true)
const itemsTableIsLoading = ref(true)

const getInvoice = async () => {
  invoiceIsLoading.value = true
  itemsTableIsLoading.value = true

  try {
    const r = await axios.get(`/invoice/${invoiceId}`)
    invoice.value = r.data.data
    items.value = calculateArr(r.data.data.Items)
  } catch (err) {
    toast.error('An unhandled exception occoured. Please check logs')
    console.error(err)
  }

  invoiceIsLoading.value = false
  itemsTableIsLoading.value = false
}

const refreshItems = async () => {
  //items.value = []
  itemsTableIsLoading.value = true

  try {
    const res = await axios.get(`/invoice/${invoiceId}/item`)
    if (res.status === 200) {
      items.value = calculateArr(res.data.data)
    } else if (res.status == 204) {
      items.value = []
    }
  } catch (err) {
    toast.error('An unhandled exception occoured. Please check logs')
    console.error(err)
  }

  itemsTableIsLoading.value = false
}

const handleSubmit = () => {
  router.push({path: `/invoice/view/${invoiceId}`})
}

onMounted(() => {
  getInvoice()
})
</script>

<template>
  <invoiceHeader
    :invoice="invoice" />
  <itemSelector
    :invoiceId="invoiceId"
    @added="refreshItems()"/>
  <invoiceItemsTable
    :items="items"
    :isLoading="itemsTableIsLoading"
    @refresh="refreshItems()" />
  <invoiceSummary
    :items="items"
    :isLoading="itemsTableIsLoading"/>
  <button class="btn btn-primary" @click="handleSubmit">Preview (Danger)</button>
</template>
