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

const router = useRouter()
const printPreview = usePrintPreview()
const printParam = usePrintParam()
const quickView = useQuickView()
const quickViewParam = useQuickViewParam()

const props = defineProps({
  params: Object
})

const isDownloading = ref(false)
const isPayJoeUploading = ref(false)
const isLexofficeUploading = ref(false)
const isAmazonUploading = ref(false)

const isPayJoeUploaded = computed(() => {
  if (!props.params?.data) return false
  return props.params.data.isUploadToPayJoe === true || props.params.data.isUploadToPayJoe === 'Y'
})

const isLexofficeUploaded = computed(() => {
  if (!props.params?.data) return false
  return props.params.data.isUploadToLexoffice === true || props.params.data.isUploadToLexoffice === 'Y'
})

const isAmazonUploaded = computed(() => {
  if (!props.params?.data) return false
  return props.params.data.isUploadToAmazon === true || props.params.data.isUploadToAmazon === 'Y'
})

const viewHandler = () => {
  if (!props.params?.data) return
  quickView.value = 'invoice'
  quickViewParam.value = props.params.data
}

const duplicateHandler = () => {
  if (!props.params?.data?.id) return
  router.push(`/sales/invoices/${props.params.data.id}/duplicate`)
}

const printHandler = () => {
  if (!props.params?.data) return
  printParam.value = props.params.data
  printPreview.value = true
}

const downloadHandler = async () => {
  if (isDownloading.value || !props.params?.data?.id) return
  isDownloading.value = true
  try {
    const response = await $fetch(`/api/invoices/${props.params.data.id}/print/PDF`, {
      headers: useRequestHeaders(['cookie'])
    })
    if (response?.reportFile) {
      const base64Response = await fetch(`data:application/pdf;base64,${response.reportFile}`)
      const blob = await base64Response.blob()
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      const invDate = props.params.data.dateInvoiced ? new Date(props.params.data.dateInvoiced).toISOString().slice(0, 10).replace(/-/g, '_') : ''
      const partnerName = (props.params.data.partner || '').replace(/[^a-zA-Z0-9]/g, '_')
      a.download = `${props.params.data.documentNo || props.params.data.id}_${partnerName}_${invDate}.pdf`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
    } else {
      toast({ message: 'Failed to download invoice PDF', type: 'is-danger', duration: 3000 })
    }
  } catch (err) {
    toast({ message: 'Failed to download invoice PDF', type: 'is-danger', duration: 3000 })
  } finally {
    isDownloading.value = false
  }
}

const editHandler = () => {
  if (!props.params?.data?.id) return
  router.push(`/windows/sales-invoices-edit/${props.params.data.id}`)
}

const deleteHandler = async () => {
  if (!props.params?.data?.id) return
  const confirmation = confirm('Are you sure want to delete this record?')
  if (confirmation) {
    await $fetch('/api/invoices/' + props.params.data.id, {
      method: 'DELETE',
      headers: useRequestHeaders(['cookie'])
    })
    location.reload()
  }
}

const quickPayment = useQuickPayment()
const quickPaymentParam = useQuickPaymentParam()

const createPaymentHandler = () => {
  if (!props.params?.data) return
  const data = props.params.data
  quickPaymentParam.value = {
    invoiceId: data.id,
    invoice: data.documentNo,
    partnerId: data.partnerId,
    partner: data.partner,
    payAmt: data.grandTotal,
    currencyId: data.currencyId,
    currency: data.currency,
    organizationId: data.organizationId,
    docBaseType: data.docBaseTypeId || data.docBaseType || ''
  }
  quickPayment.value = true
}

const uploadToPayJoe = async () => {
  if (isPayJoeUploading.value || !props.params?.data?.id) return

  isPayJoeUploading.value = true
  try {
    const res = await $fetch('/api/invoices/payjoe-upload', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: { ids: [props.params.data.id] }
    })

    if (Number(res.status) >= 400) {
      toast({ message: res.message || 'Failed to upload to PayJoe', type: 'is-danger', duration: 5000 })
    } else {
      toast({ message: res.message || 'Successfully uploaded to PayJoe', type: 'is-success', duration: 5000 })
      if (props.params.data) {
        props.params.data.isUploadToPayJoe = true
        props.params.data.uploadDatePayJoe = new Date().toISOString()
      }
      props.params.api?.refreshCells({ rowNodes: [props.params.node], force: true })
    }
  } catch (err) {
    toast({ message: 'Failed to upload to PayJoe', type: 'is-danger', duration: 5000 })
  } finally {
    isPayJoeUploading.value = false
  }
}

const uploadToLexoffice = async () => {
  if (isLexofficeUploading.value || !props.params?.data?.id) return

  isLexofficeUploading.value = true
  try {
    const res = await $fetch('/api/invoices/lexoffice-upload', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: { ids: [props.params.data.id] }
    })

    if (Number(res.status) >= 400) {
      toast({ message: res.message || 'Failed to upload to Lexoffice', type: 'is-danger', duration: 5000 })
    } else {
      toast({ message: res.message || 'Successfully uploaded to Lexoffice', type: 'is-success', duration: 5000 })
      if (props.params.data) {
        props.params.data.isUploadToLexoffice = true
        props.params.data.uploadDateLexoffice = new Date().toISOString()
      }
      props.params.api?.refreshCells({ rowNodes: [props.params.node], force: true })
    }
  } catch (err) {
    toast({ message: 'Failed to upload to Lexoffice', type: 'is-danger', duration: 5000 })
  } finally {
    isLexofficeUploading.value = false
  }
}

const uploadToAmazon = async () => {
  if (isAmazonUploading.value || !props.params?.data?.id) return

  isAmazonUploading.value = true
  try {
    const res = await $fetch('/api/invoices/amazon-upload', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: { ids: [props.params.data.id] }
    })

    if (Number(res.status) >= 400) {
      toast({ message: res.message || 'Failed to upload to Amazon', type: 'is-danger', duration: 5000 })
    } else {
      toast({ message: res.message || 'Successfully uploaded to Amazon', type: 'is-success', duration: 5000 })
      if (props.params.data) {
        props.params.data.isUploadToAmazon = true
        props.params.data.uploadDateAmazon = new Date().toISOString()
      }
      props.params.api?.refreshCells({ rowNodes: [props.params.node], force: true })
    }
  } catch (err) {
    toast({ message: 'Failed to upload to Amazon', type: 'is-danger', duration: 5000 })
  } finally {
    isAmazonUploading.value = false
  }
}
</script>

<template>
  <div v-if="params?.data" class="d-inlineFlex items-center gap-5px">
    <span class="tf-icon ti ti-file-invoice ti-sm me-1 fg-primary cursor-pointer" @click="printHandler"></span>
    <span
      class="tf-icon ti ti-sm me-1 cursor-pointer"
      :class="isDownloading ? 'ti-loader fg-gray' : 'ti-download fg-primary'"
      title="Download PDF"
      @click="downloadHandler"
    ></span>
    <span class="tf-icon ti ti-copy ti-sm me-1 fg-info cursor-pointer" @click="duplicateHandler"></span>
    <span class="tf-icon ti ti-plus ti-sm me-1 fg-success cursor-pointer" title="Create Payment" @click="createPaymentHandler"></span>
    <span v-if="params.data.docStatusId !== 'CO' && params.data.docStatusId !== 'VO'" class="tf-icon ti ti-pencil ti-sm me-1 fg-warning cursor-pointer" @click="editHandler"></span>
    <span v-if="params.data.docStatusId !== 'CO' && params.data.docStatusId !== 'VO'" class="tf-icon ti ti-trash ti-sm me-1 fg-danger cursor-pointer" @click="deleteHandler"></span>
  </div>
</template>
