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

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

import invoiceHeader from './../components/invoice_header.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 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 = calculate(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 handlePrint = () => {
  print()
}

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

<template>
  <invoiceHeader
    :invoice="invoice" />
  <invoiceItemsTable
    :items="items"
    :isLoading="itemsTableIsLoading" />
  <invoiceSummary
    :items="items"
    :isLoading="itemsTableIsLoading"
  />
  <button id="print-button" class="btn btn-primary" @click="handlePrint">Print</button>
</template>

<style>
@media print {
  #sidebar, #navbar, #print-button, .btn {
    display: none !important;
  }
}
</style>
