import jsPDF from 'jspdf'
// @ts-ignore
import jspdfBarcode from 'jspdf-barcode'
import { _optn, _applicationNo, _date, _name, _type, _location, _assessor, _feeList, _codeList, _amountList, _signatureAssessor, _signatureApprover, _assessorid, _approvedDate, _assessedDate, _units, _totalUnits, _floorArea, _additional, _additionalAmountList, _additionalCodeList, _additionalFeeList, _additionalUnitList } from '../../stores/pdfinfo'
import dayjs from 'dayjs'
// @ts-ignore
import QRCode from 'qrcode'
import { SHA384, MD5 } from 'crypto-js'

export default async () => {
  const PESO = import.meta.env.VITE_PESO

  const OPTN = _optn.get()
  const APPLICATION = _applicationNo.get()
  const DATE = _date.get()
  const NAME = _name.get()
  const LOCATION = _location.get()
  const TYPE = _type.get()
  const ASSESSOR = _assessor.get()
  const APPROVER = 'AR. KHASHAYAR L. TOGHYANI'
  const FEES = _feeList.get()
  const CODES = _codeList.get()
  const AMOUNTS = _amountList.get()
  const ASSESSORID = _assessorid.get()
  const APPROVERID = 276
  const UNITS = _units.get()
  const TOTALUNITS = _totalUnits.get()
  const FLOORAREA = _floorArea.get()

  const MULTIPLIED = AMOUNTS.map((amount) => parseInt(amount) * UNITS)

  const ADDTLFEES = _additionalFeeList.get()
  const ADDTLAMOUNTS = _additionalAmountList.get()
  const ADDTLCODES = _additionalCodeList.get()
  const ADDTLUNITS = _additionalUnitList.get()

  const ADDTLMULTIPLIED = ADDTLAMOUNTS.map((amount, index) => parseInt(amount) * ADDTLUNITS[index])

  const doc = new jsPDF({
    orientation: 'p',
    unit: 'mm',
    format: 'letter',
  })

  const arial =
    '[encoded data, 1220284 characters]'
  doc.addFileToVFS('arial-normal.ttf', arial)
  doc.addFont('arial-normal.ttf', 'arial', 'normal')

  var arialbold =
    '[encoded data, 177628 characters]'
  doc.addFileToVFS('arial-bold-bold.ttf', arialbold)
  doc.addFont('arial-bold-bold.ttf', 'arial-bold', 'bold')

  const getTextWidth = (text: string, fontSize: number) => {
    doc.setFontSize(fontSize)
    return doc.getStringUnitWidth(text) * fontSize * 0.35
  }

  const pageWidth = doc.internal.pageSize.getWidth()

  const lungsod = new Image()
  lungsod.src = 'lungsod.png'

  const ocbo = new Image()
  ocbo.src = 'ocbologo.png'

  jspdfBarcode(doc, APPLICATION, {
    fontSize: 32,
    textColor: '#000000',
    x: pageWidth - 35,
    y: 38,
    textOptions: { align: 'center' },
  })

  const generateQR = async (text: string) => {
    return await QRCode.toDataURL(text)
  }

  const assessorFirstHash = SHA384(ASSESSORID.toString())
  const assessorSecondHash = MD5(assessorFirstHash.toString().substring(9))
  const assessorQrText = `Use OCBO e-Sign Validator - scanid=${assessorSecondHash.toString().substring(24)}`
  const assessorQr = await generateQR(assessorQrText)

  const approverHash = SHA384(APPROVERID.toString())
  const approverSecondHash = MD5(approverHash.toString().substring(9))
  const approverQrText = `Use OCBO e-Sign Validator - scanid=${approverSecondHash.toString().substring(24)}`
  const approverQr = await generateQR(approverQrText)

  // const lungsodItem = document.getElementById('lungsod')
  // const lungsodSrc = lungsodItem?.getAttribute('src')
  // const lungsodLink = document.createElement('a')
  // lungsodLink.href = lungsodSrc ?? ''

  // const ocboItem = document.getElementById('ocbo')
  // const ocboSrc = ocboItem?.getAttribute('src')
  // const ocboLink = document.createElement('a')
  // ocboLink.href = ocboSrc ?? ''

  const republicText = 'Republic of the Philippines'
  const republicTextWidth = getTextWidth(republicText, 9)
  const officeText = 'OFFICE OF THE CITY BUILDING OFFICIAL'
  const officeTextWidth = getTextWidth(officeText, 10)
  const cityText = 'City of Davao'
  const cityTextWidth = getTextWidth(cityText, 9)

  const republicTextX = (pageWidth - republicTextWidth) / 2
  const officeTextX = (pageWidth - officeTextWidth) / 2
  const cityTextX = (pageWidth - cityTextWidth) / 2

  doc.setFont('arial', 'normal')
  doc.setFontSize(9)
  doc.text(republicText, republicTextX, 14)
  doc.setFont('arial-bold', 'bold')
  doc.setFontSize(10)
  doc.text(officeText, officeTextX, 19)
  doc.setFont('arial', 'normal')
  doc.setFontSize(9)
  doc.text(cityText, cityTextX, 24)

  doc.addImage(lungsod, 'PNG', 14, 8, 18, 18, 'lungsod', 'NONE', 0)
  doc.addImage(ocbo, 'PNG', pageWidth - 34, 8, 18, 18, 'ocbo', 'NONE', 0)

  const opText = 'ORDER OF PAYMENT'
  const opTextWidth = getTextWidth(opText, 8.75)
  const opTextX = (pageWidth - opTextWidth) / 2
  doc.setFont('arial-bold', 'bold')
  doc.setFontSize(9)
  doc.text(opText, opTextX, 34)

  const divisionText = 'OCCUPANCY PERMIT'
  const divisionTextWidth = getTextWidth(divisionText, 7.25)
  const divisionTextX = (pageWidth - divisionTextWidth) / 2
  doc.setFont('arial', 'normal')
  doc.setFontSize(8)
  doc.text(divisionText, divisionTextX, 38)

  const optnText = 'OPTN:'
  const optnTextX = 16
  doc.setFont('arial-bold', 'bold')
  doc.setFontSize(8)
  doc.text(optnText, optnTextX, 38)

  const optnContentX = 25
  doc.setFontSize(8)
  doc.text(OPTN, optnContentX, 38)

  const toText = `TO: The City Treasurer's Office`
  const toTextX = 16
  doc.setFont('arial', 'normal')
  doc.setFontSize(8)
  doc.text(toText, toTextX, 46)

  doc.text('Please accept payment for fee specified hereunder', 16, 50)

  doc.text('Application No. :', pageWidth - 60, 46)

  doc.setFont('arial-bold', 'bold')
  doc.text(APPLICATION, pageWidth - 38, 46)

  doc.setFont('arial', 'normal')
  doc.text('Approved Date :', pageWidth - 60, 50)

  doc.setFont('arial-bold', 'bold')
  doc.text(DATE, pageWidth - 38, 50)

  doc.setFont('arial', 'normal')
  doc.text('Name of Applicant :', 23.4, 58)

  doc.setFont('arial-bold', 'bold')
  doc.text(NAME, 50, 58)

  doc.setFont('arial', 'normal')
  doc.text('Location of Construction :', 16, 62)

  doc.setFont('arial-bold', 'bold')
  doc.text(LOCATION, 50, 62)

  doc.setFont('arial', 'normal')
  doc.text('Type of Use :', 31.2, 66)

  doc.setFont('arial-bold', 'bold')
  doc.text(TYPE, 50, 66)

  doc.text('ACCOUNT DESCRIPTION', 16, 74)
  doc.text('ACCOUNT CODE', getTextWidth('ACCOUNT DESCRIPTION', 8) + 40, 74)
  doc.text('AMOUNT', getTextWidth('ACCOUNT DESCRIPTION', 8) + getTextWidth('ACCOUNT CODE', 8) + 65, 74)
  doc.text('UNIT', getTextWidth('ACCOUNT DESCRIPTION', 8) + getTextWidth('ACCOUNT CODE', 8) + 82, 74)

  doc.setFont('arial', 'normal')

  let yPosition = 82
  FEES.forEach((fee) => {
    doc.text(fee, 16, yPosition)
    yPosition += 4
  })

  yPosition = 82
  CODES.forEach((code) => {
    doc.text(code, 76, yPosition)
    yPosition += 4
  })

  yPosition = 82
  AMOUNTS.forEach((amount) => {
    doc.text(`${PESO} ${parseInt(amount).toLocaleString('en-US', { minimumFractionDigits: 2 })}`, 122, yPosition)
    yPosition += 4
  })

  yPosition = 82
  AMOUNTS.forEach(() => {
    doc.text(`x${UNITS}`, 140, yPosition)
    yPosition += 4
  })

  yPosition = 82
  AMOUNTS.forEach(() => {
    doc.text('=', 148, yPosition)
    yPosition += 4
  })

  yPosition = 82
  MULTIPLIED.forEach((amount) => {
    doc.text(`${PESO} ${parseInt(amount.toString()).toLocaleString('en-US', { minimumFractionDigits: 2 })}`, 156, yPosition)
    yPosition += 4
  })

  let newYPosition = yPosition

  doc.line(156, newYPosition, 170, newYPosition)

  doc.setFont('arial', 'normal')
  doc.text(`${PESO}`, 156, newYPosition + 4)

  doc.setFont('arial-bold', 'bold')
  doc.text('Total :', 146, newYPosition + 4)
  const totalAmount = MULTIPLIED.reduce((sum, amount) => sum + parseFloat(amount.toString()), 0)
  doc.text(`${totalAmount.toLocaleString('en-US', { minimumFractionDigits: 2 })}`, 159, newYPosition + 4)

  doc.text('No. of Units:', 16, newYPosition + 4)
  doc.text(TOTALUNITS.toString(), 34, newYPosition + 4)
  doc.text('Actual Floor Area:', 16, newYPosition + 8)
  doc.text(FLOORAREA.toLocaleString('en-US', { minimumFractionDigits: 2 }), 42, newYPosition + 8)

  doc.text('Assessed By :', 16, newYPosition + 16)
  doc.text('Approved By :', 142, newYPosition + 16)

  doc.text(ASSESSOR, 16, newYPosition + 34)
  doc.text(APPROVER, 142, newYPosition + 34)

  doc.addImage(assessorQr, 'PNG', 16, newYPosition + 18, 14, 14, 'assessorQr', 'NONE', 0)
  doc.addImage(_signatureAssessor.get(), 'PNG', 30, newYPosition + 18, 10, 5.9, 'signatureAssessor', 'NONE', 0)
  doc.setFont('arial', 'normal')
  doc.setFontSize(4)
  doc.text('Digitally signed by :', 30, newYPosition + 26)
  doc.text(ASSESSOR, 30, newYPosition + 28)
  doc.text('Date: ' + dayjs(_assessedDate.get()).format('YYYY-MM-DD HH:mm:ss'), 30, newYPosition + 30)

  doc.addImage(approverQr, 'PNG', 142, newYPosition + 18, 14, 14, 'approverQr', 'NONE', 0)
  doc.addImage(_signatureApprover.get(), 'PNG', 156, newYPosition + 18, 41.4, 5.9, 'signatureApprover', 'NONE', 0)
  doc.text('Digitally signed by :', 156, newYPosition + 26)
  doc.text(APPROVER, 156, newYPosition + 28)
  doc.text('Date: ' + dayjs(_approvedDate.get()).format('YYYY-MM-DD HH:mm:ss'), 156, newYPosition + 30)

  doc.setFont('arial-bold', 'bold')
  doc.setFontSize(7)
  doc.text('Please use the OPTN when paying online.', 16, newYPosition + 44)
  const note = doc.splitTextToSize('Note: The 72 Hours Transaction Policy of the City Mayor, shall commence upon submission of the Bureau of Fire Protection clearance/certificate and other requirement stated in the notice to comply to be issued by this office.', newYPosition + 50)
  doc.text(note, 16, newYPosition + 48)

  doc.setFont('arial', 'normal')
  doc.setFontSize(6)
  doc.text('Officer-in-Charge', 154, newYPosition + 37)

  if (_additional.get()) {
    doc.addPage('letter')

    jspdfBarcode(doc, APPLICATION, {
      fontSize: 32,
      textColor: '#000000',
      x: pageWidth - 35,
      y: 38,
      textOptions: { align: 'center' },
    })

    doc.setFont('arial', 'normal')
    doc.setFontSize(9)
    doc.text(republicText, republicTextX, 14)
    doc.setFont('arial-bold', 'bold')
    doc.setFontSize(10)
    doc.text(officeText, officeTextX, 19)
    doc.setFont('arial', 'normal')
    doc.setFontSize(9)
    doc.text(cityText, cityTextX, 24)

    doc.addImage(lungsod, 'PNG', 14, 8, 18, 18, 'lungsod', 'NONE', 0)
    doc.addImage(ocbo, 'PNG', pageWidth - 34, 8, 18, 18, 'ocbo', 'NONE', 0)

    const opText = 'ORDER OF PAYMENT'
    const opTextWidth = getTextWidth(opText, 8.75)
    const opTextX = (pageWidth - opTextWidth) / 2
    doc.setFont('arial-bold', 'bold')
    doc.setFontSize(9)
    doc.text(opText, opTextX, 34)

    const divisionText = 'BUILDING ADDITIONAL PERMIT'
    const divisionTextWidth = getTextWidth(divisionText, 7.25)
    const divisionTextX = (pageWidth - divisionTextWidth) / 2
    doc.setFont('arial', 'normal')
    doc.setFontSize(8)
    doc.text(divisionText, divisionTextX, 38)

    const optnText = 'OPTN:'
    const optnTextX = 16
    doc.setFont('arial-bold', 'bold')
    doc.setFontSize(8)
    doc.text(optnText, optnTextX, 38)

    const optnContentX = 25
    doc.setFontSize(8)
    doc.text(OPTN, optnContentX, 38)

    const toText = `TO: The City Treasurer's Office`
    const toTextX = 16
    doc.setFont('arial', 'normal')
    doc.setFontSize(8)
    doc.text(toText, toTextX, 46)

    doc.text('Please accept payment for fee specified herunder', 16, 50)

    doc.text('Application No. :', pageWidth - 60, 46)

    doc.setFont('arial-bold', 'bold')
    doc.text(APPLICATION, pageWidth - 38, 46)

    doc.setFont('arial', 'normal')
    doc.text('Approved Date :', pageWidth - 60, 50)

    doc.setFont('arial-bold', 'bold')
    doc.text(DATE, pageWidth - 38, 50)

    doc.setFont('arial', 'normal')
    doc.text('Name of Applicant :', 23.4, 58)

    doc.setFont('arial-bold', 'bold')
    doc.text(NAME, 50, 58)

    doc.setFont('arial', 'normal')
    doc.text('Location of Construction :', 16, 62)

    doc.setFont('arial-bold', 'bold')
    doc.text(LOCATION, 50, 62)

    doc.setFont('arial', 'normal')
    doc.text('Type of Use :', 31.2, 66)

    doc.setFont('arial-bold', 'bold')
    doc.text(TYPE, 50, 66)

    doc.text('ACCOUNT DESCRIPTION', 16, 74)
    doc.text('ACCOUNT CODE', getTextWidth('ACCOUNT DESCRIPTION', 8) + 40, 74)
    doc.text('AMOUNT', getTextWidth('ACCOUNT DESCRIPTION', 8) + getTextWidth('ACCOUNT CODE', 8) + 65, 74)
    doc.text('UNIT', getTextWidth('ACCOUNT DESCRIPTION', 8) + getTextWidth('ACCOUNT CODE', 8) + 82, 74)

    doc.setFont('arial', 'normal')

    let yPosition = 82
    ADDTLFEES.forEach((fee) => {
      doc.text(fee, 16, yPosition)
      yPosition += 4
    })

    yPosition = 82
    ADDTLCODES.forEach((code) => {
      doc.text(code, 76, yPosition)
      yPosition += 4
    })

    yPosition = 82
    ADDTLAMOUNTS.forEach((amount) => {
      doc.text(`${PESO} ${parseInt(amount).toLocaleString('en-US', { minimumFractionDigits: 2 })}`, 122, yPosition)
      yPosition += 4
    })

    yPosition = 82
    ADDTLAMOUNTS.forEach(() => {
      doc.text(`x${UNITS}`, 140, yPosition)
      yPosition += 4
    })

    yPosition = 82
    ADDTLAMOUNTS.forEach(() => {
      doc.text('=', 148, yPosition)
      yPosition += 4
    })

    yPosition = 82
    ADDTLMULTIPLIED.forEach((amount) => {
      doc.text(`${PESO} ${parseInt(amount.toString()).toLocaleString('en-US', { minimumFractionDigits: 2 })}`, 156, yPosition)
      yPosition += 4
    })

    let newYPosition = yPosition

    doc.line(156, newYPosition, 170, newYPosition)

    doc.setFont('arial', 'normal')
    doc.text(`${PESO}`, 156, newYPosition + 4)

    doc.setFont('arial-bold', 'bold')
    doc.text('Total :', 146, newYPosition + 4)
    const totalAmount = ADDTLMULTIPLIED.reduce((sum, amount) => sum + parseFloat(amount.toString()), 0)
    doc.text(`${totalAmount.toLocaleString('en-US', { minimumFractionDigits: 2 })}`, 159, newYPosition + 4)

    doc.text('No. of Units:', 16, newYPosition + 4)
    doc.text(TOTALUNITS.toString(), 34, newYPosition + 4)
    doc.text('Actual Floor Area:', 16, newYPosition + 8)
    doc.text(FLOORAREA.toLocaleString('en-US', { minimumFractionDigits: 2 }), 42, newYPosition + 8)

    doc.text('Assessed By :', 16, newYPosition + 16)
    doc.text('Approved By :', 142, newYPosition + 16)

    doc.text(ASSESSOR, 16, newYPosition + 34)
    doc.text(APPROVER, 142, newYPosition + 34)

    doc.addImage(assessorQr, 'PNG', 16, newYPosition + 18, 14, 14, 'assessorQr', 'NONE', 0)
    doc.addImage(_signatureAssessor.get(), 'PNG', 30, newYPosition + 18, 10, 5.9, 'signatureAssessor', 'NONE', 0)
    doc.setFont('arial', 'normal')
    doc.setFontSize(4)
    doc.text('Digitally signed by :', 30, newYPosition + 26)
    doc.text(ASSESSOR, 30, newYPosition + 28)
    doc.text('Date: ' + dayjs(_assessedDate.get()).format('YYYY-MM-DD HH:mm:ss'), 30, newYPosition + 30)

    doc.addImage(approverQr, 'PNG', 142, newYPosition + 18, 14, 14, 'approverQr', 'NONE', 0)
    doc.addImage(_signatureApprover.get(), 'PNG', 156, newYPosition + 18, 41.4, 5.9, 'signatureApprover', 'NONE', 0)
    doc.text('Digitally signed by :', 156, newYPosition + 26)
    doc.text(APPROVER, 156, newYPosition + 28)
    doc.text('Date: ' + dayjs(_approvedDate.get()).format('YYYY-MM-DD HH:mm:ss'), 156, newYPosition + 30)

    doc.setFont('arial-bold', 'bold')
    doc.setFontSize(7)
    doc.text('Please use the OPTN when paying online.', 16, newYPosition + 44)
    const note = doc.splitTextToSize('Note: The 72 Hours Transaction Policy of the City Mayor, shall commence upon submission of the Bureau of Fire Protection clearance/certificate and other requirement stated in the notice to comply to be issued by this office.', newYPosition + 50)
    doc.text(note, 16, newYPosition + 48)

    doc.setFont('arial', 'normal')
    doc.setFontSize(6)
    doc.text('Officer-in-Charge', 154, newYPosition + 37)
  }

  doc.save(`OP-${APPLICATION}.pdf`)
}
