<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>
  <div id="print-preview" class="bg-white text-black">
    <invoiceHeader
      :invoice="invoice" />
    <invoiceItemsTable
      preview=true
      :items="items"
      :isLoading="itemsTableIsLoading" />
    <invoiceSummary
      :items="items"
      :isLoading="itemsTableIsLoading"
    />
  </div>
  <button id="print-button" class="btn btn-primary" @click="handlePrint">Print</button>
</template>

<style>
#print-preview {
  width: 670px;
}
#print-preview * {
  font-size: 12pt !important;
}
#print-preview .sup {
}
#print-preview table {
  width: 100%;
}
#print-preview table * {
  font-size: 10pt !important;
}
#print-preview .invoice-items-table {
  margin-bottom: auto !important;
}
#print-preview .invoice-summary {
  margin-top: auto !important;
}
#print-preview .item-name-cell span {
  max-width: 150pt !important;
}
@media print {
  body {
    background-color: white;
  }
  #print-preview {
    width: auto !important;
    height: 100% !important;
  }
  #sidebar, #navbar, #print-button, .btn {
    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>
