<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, { InvoiceTotal } from "./../classes/invoice"
import { calculateArr, calculateTotal } from "./../classes/invoice_item"

import PrintPreview from './../components/PrintPreview.vue'

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

const route = useRoute()

const invoiceId = route.params.id
const invoice = ref(new Invoice())
const total = ref(new InvoiceTotal())

const invoiceIsLoading = ref(true)

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

  try {
    const r = await axios.get(`/invoice/${invoiceId}`)
    const items = calculateArr(r.data.data.Items)

    invoice.value = {
      ...r.data.data, 
      Items: items
    }

    total.value = calculateTotal(items)
  } catch (err) {
    toast.error('An unhandled exception occoured. Please check logs')
    console.error(err)
  }

  invoiceIsLoading.value = false
}

const handlePrint = () => {
  print()
}

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

<template>
  <div id="print-preview" class="bg-white text-black">
    <PrintPreview :invoice="invoice" :total="total"/>
  </div>
  <button id="print-button" class="btn btn-primary" @click="handlePrint">Print</button>
</template>

<style>
#print-preview {
  max-height: 90vh;
  display: none;
  aspect-ratio: 1 / 1.414;
}
@media print {
  @page {
    size: A4 portrait;
  }
  body {
    background-color: white;
  }
  #print-preview {
    display: block;
    width: 100% !important;
    height: 100% !important;
  }
  #sidebar, #navbar, #print-button, .btn, .v-toast {
    display: none !important;
  }
  ::-webkit-scrollbar {
    display: none;
  }
  main {
    width: 100% !important;
    overflow-x: visible !important;
    margin: 0 !important;
    padding: 0 !important;
  }
  #app {
    display: block;
    max-height: auto !important;
    overflow-y: visible !important;
  }
}
</style>
