import { PDFDocument } from 'pdf-lib'
import { saveAs } from 'file-saver'
import pdf from '../../assets/carte_etudiant.pdf'
import pdf2 from '../../assets/arriere.pdf'
import pdf3 from '../../assets/business_card_template_001_form.pdf'
import QRCode from 'qrcode'

const PDFEditor = async (data) => {
  // Load the existing PDF files
  const existingPdfBytes = await fetch(pdf).then((res) => res.arrayBuffer())
  const existingPdfBytes2 = await fetch(pdf2).then((res) => res.arrayBuffer())
  const existingPdfBytes3 = await fetch(pdf3).then((res) => res.arrayBuffer())

  // Load the PDFs
  const pdfDoc = await PDFDocument.load(existingPdfBytes)
  const pdfDoc2 = await PDFDocument.load(existingPdfBytes2)
  const pdfDoc3 = await PDFDocument.load(existingPdfBytes3)

  // Get the form from the first PDF (front)
  const form = pdfDoc.getForm()
  form.getTextField('name').setText(data.f1)
  form.getTextField('birthday').setText('Date de naissance: ' + data.f2)
  form.getTextField('niveau').setText('Niveau: ' + data.f3)
  form.getTextField('annee').setText('Année Univesitaire: ' + data.f4)
  form.getTextField('num_inscription').setText("Numéro d'inscription: " + data.f5)
  form.flatten()

  // ----------------------------------------- carte frontale ----------------------------------------------------
  const canvas = document.createElement('canvas')
  const context = canvas.getContext('2d')
  const diameter = 90
  const resolutionScale = 4
  canvas.width = diameter * resolutionScale
  canvas.height = diameter * resolutionScale

  const base64Data = data.f8.split(',')[1]
  const img = new Image()
  img.src = `data:image/png;base64,${base64Data}`

  await new Promise((resolve) => {
    img.onload = resolve
  })

  context.scale(resolutionScale, resolutionScale)
  context.beginPath()
  context.arc(diameter / 2, diameter / 2, diameter / 2, 0, Math.PI * 2)
  context.closePath()
  context.clip()
  context.drawImage(img, 0, 0, diameter, diameter)

  const canvasImageBase64 = canvas.toDataURL('image/png')
  const canvasImageBytes = Uint8Array.from(atob(canvasImageBase64.split(',')[1]), (char) =>
    char.charCodeAt(0)
  )

  const image = await pdfDoc.embedPng(canvasImageBytes)
  const page = pdfDoc.getPage(0)
  page.drawImage(image, {
    x: 74 - diameter / 2,
    y: 77 - diameter / 2,
    width: diameter,
    height: diameter
  })

  const form2 = pdfDoc2.getForm()
  const form3 = pdfDoc3.getForm()
  const field = form2.getField('f6')
  if (field) {
    form2.removeField(field)
    form3.removeField(field)
  }

  // ----------------------------------------------- carte arriere -------------------------------------------
  const paperContent = `
    CUniversity
    Nom et prénom: ${data.f1}
    Date de naissance: ${data.f2}
    Niveau: ${data.f3}
    Année Univesitaire: ${data.f4}
    Numéro d'inscription: ${data.f5}
  `

  const qrCanvas = document.createElement('canvas')
  const qrWidth = 300
  QRCode.toCanvas(
    qrCanvas,
    paperContent,
    { errorCorrectionLevel: 'H', width: qrWidth },
    (error) => {
      if (error) {
        console.error(error)
        return
      }

      const qrImageBase64 = qrCanvas.toDataURL('image/png')
      const qrImageBytes = Uint8Array.from(atob(qrImageBase64.split(',')[1]), (char) =>
        char.charCodeAt(0)
      )

      ;(async () => {
        const page2 = pdfDoc2.getPage(0)
        const qrImage = await pdfDoc2.embedPng(qrImageBytes)

        const x = 7
        const y = 75
        const qrSize = 95

        page2.drawImage(qrImage, {
          x,
          y,
          width: qrSize,
          height: qrSize
        })

        // Merge the front and back (pages) into a new document
        const newPdfDoc = await PDFDocument.create()
        // const [frontPage] = await newPdfDoc.copyPages(pdfDoc, [0]); // Front page
        const [frontPage] = await newPdfDoc.copyPages(pdfDoc3, [0]) // Front page
        const [backPage] = await newPdfDoc.copyPages(pdfDoc2, [0]) // Back page

        newPdfDoc.addPage(frontPage)
        newPdfDoc.addPage(backPage)

        const pdfBytes = await newPdfDoc.save()

        // Trigger the download of the merged PDF
        const blob = new Blob([pdfBytes], { type: 'application/pdf' })
        saveAs(blob, `carte_etudiant_${data.f1}.pdf`)
      })()
    }
  )
}

export default PDFEditor
