<script setup>
import { date } from 'alga-js'
import { toast } from 'bulma-toast'

const batchPrintPreview = useBatchPrintPreview()
const batchPrintParam = useBatchPrintParam()
const user = useCookie('logship_user')

const props = defineProps({
  modelName: String
})

const pdfSrc = ref('')
const isLoading = ref(false)
const printInfo = ref({ totalInvoices: 0, requestedInvoices: 0 })

const pdfPreview = async () => {
  if (!batchPrintParam.value?.length) return

  isLoading.value = true
  try {
    const response = await $fetch('/api/' + props.modelName + '/batch-print', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: {
        ids: batchPrintParam.value.map(item => item.id),
        type: 'PDF'
      }
    })

    if (response?.reportFile) {
      printInfo.value = {
        totalInvoices: response.totalInvoices || 0,
        requestedInvoices: response.requestedInvoices || 0
      }
      const base64Response = await fetch(`data:application/pdf;base64,${response.reportFile}`)
      const blob = await base64Response.blob()
      pdfSrc.value = URL.createObjectURL(blob)
    } else if (response?.status >= 400) {
      toast({
        message: response.message || 'Failed to generate batch print',
        type: 'is-danger',
        duration: 3000
      })
    }
  } catch (err) {
    console.error('Batch print error:', err)
    toast({
      message: 'Failed to generate batch print',
      type: 'is-danger',
      duration: 3000
    })
  } finally {
    isLoading.value = false
  }
}
watch(batchPrintPreview, (newVal) => {
  if (newVal) {
    pdfPreview()
  }
})

const closeBatchPrintPreview = () => {
  batchPrintPreview.value = false
  pdfSrc.value = ''
  batchPrintParam.value = []
  printInfo.value = { totalInvoices: 0, requestedInvoices: 0 }
}

const printReport = async (fileType) => {
  if (!batchPrintParam.value?.length) return

  isLoading.value = true
  try {
    const response = await $fetch('/api/' + props.modelName + '/batch-print', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: {
        ids: batchPrintParam.value.map(item => item.id),
        type: fileType
      }
    })

    if (response?.reportFile) {
      let mimeType = 'application/pdf'
      const base64Response = await fetch(`data:${mimeType};base64,${response.reportFile}`)
      const blob = await base64Response.blob()
      const blobUrl = URL.createObjectURL(blob)
      open(blobUrl, '_blank')
    }
  } catch (err) {
    console.error('Batch print error:', err)
    toast({
      message: 'Failed to generate batch print',
      type: 'is-danger',
      duration: 3000
    })
  } finally {
    isLoading.value = false
  }
}

const serverSidePrinting = async (content) => {
  const res = await $fetch('/api/print/', {
    method: 'POST',
    body: content
  })
  if (res) {
    console.log(res)
    if (res?.stdout) {
      toast({
        message: 'The documents have been printed via server side printing!',
        type: 'is-success',
        duration: 2000
      })
    }
  }
}

const printServer = async () => {
  if (!batchPrintParam.value?.length) return

  isLoading.value = true
  try {
    const response = await $fetch('/api/' + props.modelName + '/batch-print', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: {
        ids: batchPrintParam.value.map(item => item.id),
        type: 'PDF'
      }
    })

    if (response?.reportFile) {
      serverSidePrinting({
        pathName: `${props.modelName?.replaceAll('/', '-')}/${new Date().getFullYear()}`,
        fileName: `${date.now().replace(/\-|\:/g, '_').replace(' ', '-BATCH-')}-${props.modelName?.replaceAll('/', '-')?.toUpperCase()}-${user.value?.Name || 'SUPERUSER'}.pdf`,
        fileContent: response.reportFile
      })
    }
  } catch (err) {
    console.error('Server side print error:', err)
    toast({
      message: 'Failed to send to print server',
      type: 'is-danger',
      duration: 3000
    })
  } finally {
    isLoading.value = false
  }
}

const dropDownHandler = (e) => {
  if (e.target.parentElement.classList.contains('show')) {
    e.target.parentElement.classList.remove('show')
  } else {
    e.target.parentElement.classList.add('show')
  }
}

const dropItemHandler = (e) => {
  if (e.target.parentElement.parentElement.classList.contains('show')) {
    e.target.parentElement.parentElement.classList.remove('show')
  } else {
    e.target.parentElement.parentElement.classList.add('show')
  }
}
</script>

<template>
  <div class="modal" :class="{'active': batchPrintPreview}" :style="{display: batchPrintPreview ? 'block' : 'none'}">
    <div class="modalDialog modalCenter modalPrintPreview" @click.self="closeBatchPrintPreview">
      <div class="modalContent">
        <div class="modalHeader">
          <h3 class="modalTitle">
            Batch Print Preview
            <span v-if="printInfo.totalInvoices > 0" class="fg-info" style="font-size: 0.875rem; margin-left: 10px;">
              ({{ printInfo.totalInvoices }} of {{ printInfo.requestedInvoices }} invoices)
            </span>
          </h3>
          <div class="cursor-pointer" @click="closeBatchPrintPreview">
            <span class="tf-icon ti ti-x ti-sm me-1"></span>
          </div>
        </div>
        <div class="modalBody">
          <div class="d-flex justify-between mb-3">
            <h4></h4>
            <div class="d-flex gap-0.75rem">
              <div>
                <button type="button" class="button" @click="printServer" :disabled="isLoading">
                  <span class="tf-icon ti ti-printer ti-xs me-1 color-inherit"></span> Print Server
                </button>
              </div>
              <div class="dropDown">
                <button type="button" class="button dropDownToggler" @click="dropDownHandler" :disabled="isLoading">
                  <span class="tf-icon ti ti-file-export ti-xs me-1 color-inherit"></span> Print Report
                </button>
                <div class="dropDownBackdrop" @click="dropDownHandler"></div>
                <div class="dropDownMenu dropDownRight">
                  <span class="dropDownItem" @click="dropItemHandler($event); printReport('PDF');">Print Report in PDF</span>
                </div>
              </div>
            </div>
          </div>
          <div>
            <div v-if="isLoading" class="my-5 mx-5 text-center">
              <span class="tf-icon ti ti-loader ti-lg spin"></span>
              <p>Loading {{ batchPrintParam.length }} invoices...</p>
            </div>
            <div v-else class="my-5 mx-5">
              <ClientOnly v-if="pdfSrc !== ''">
                <PrintViewer :url="pdfSrc" />
              </ClientOnly>
            </div>
          </div>
        </div>
        <div class="modalFooter">
          <div></div>
          <div class="d-flex gap-10px">
            <button type="button" class="button" @click="closeBatchPrintPreview">Close</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.modal.active .modalDialog {
  padding: 0;
}
.modalContent {
  background: white;
}

.spin {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
