import { PDFDocument, rgb } from 'pdf-lib'
import PDF from '../../assets/business_card_template_001_form.pdf'
import PDF2 from '../../assets/business_card_template_002.pdf'
import QRCode from 'qrcode'
import { saveAs } from 'file-saver'

async function fillPdfFields(jsonData) {
  const response = await fetch(PDF) // Load the PDF file
  const response2 = await fetch(PDF2) // Load the second PDF file
  const pdfBytes = await response.arrayBuffer()
  const pdfBytes2 = await response2.arrayBuffer()
  const pdfDoc = await PDFDocument.load(pdfBytes)
  const pdfDoc2 = await PDFDocument.load(pdfBytes2)

  // Get the first page to draw text on
  const page = pdfDoc.getPage(0)
  const form = pdfDoc.getForm()

  const nameField = form.getTextField('name')
  nameField.setText(jsonData.f1 || '')

  const birthdayField = form.getTextField('birthday')
  birthdayField.setText(jsonData.f2 || '')

  const niveauField = form.getTextField('niveau')
  niveauField.setText(jsonData.f3 || '')

  const anneeField = form.getTextField('annee')
  anneeField.setText(jsonData.f4 || '')

  const num_inscriptionField = form.getTextField('num_inscription')
  num_inscriptionField.setText(jsonData.f5 || '')
  console.log('namefield:', nameField.getText())
  console.log('namefield:', birthdayField.getText())
  console.log('namefield:', niveauField.getText())
  console.log('namefield:', anneeField.getText())
  console.log('namefield:', num_inscriptionField.getText())
  
  // Define positions for text (adjust these coordinates based on your red dots)
  // const textPositions = [
  //   { x: 45, y: 92, text: `${jsonData.f1 || ''}`, fontSize: 10 }, // Nom et prénom
  //   { x: 45, y: 75, text: `${jsonData.f2 || ''}`, fontSize: 10 }, // Date de naissance
  //   { x: 45, y: 58, text: `${jsonData.f3 || ''}`, fontSize: 10 }, // Niveau
  //   { x: 45, y: 38, text: `${jsonData.f4 || ''}`, fontSize: 10 }, // Année Univesitaire
  //   { x: 60, y: 23, text: `${jsonData.f5 || ''}`, fontSize: 10 }  // Numéro d'inscription
  // ]

  // Draw text at specified positions
  // textPositions.forEach((item, index) => {
  //   if (item.text.trim()) {
  //     page.drawText(item.text, {
  //       x: item.x,
  //       y: item.y,
  //       size: item.fontSize - 2,
  //       color: rgb(1, 1, 1), // Black text
  //     })
  //     console.log(`Drawing text at position ${index + 1}: ${item.text} at (${item.x}, ${item.y})`)
  //   }
  // })

  // ---------------------------------calculate and paste the image in pdf--------------------------------------
  if (jsonData.f8) {
    const diameter = 90
    const resolutionScale = 4

    const canvas = document.createElement('canvas')
    const context = canvas.getContext('2d')
    canvas.width = diameter * resolutionScale
    canvas.height = diameter * resolutionScale

    const base64Data = jsonData.f8.startsWith('data:image')
      ? jsonData.f8.split(',')[1]
      : jsonData.f8 // Handle case where "data:image/png;base64," is missing

    const img = new Image()
    await new Promise((resolve, reject) => {
      img.onload = resolve
      img.onerror = reject
      img.src = `data:image/png;base64,${base64Data}`
    })

    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 image = await pdfDoc.embedPng(canvasImageBase64)

    page.drawImage(image, {
      x: 186.4 - diameter / 2, // Keep the same X position
      y: 90 - diameter / 2, // Keep the same Y position
      width: diameter * 0.8, // Reduce size (e.g., 70% of original)
      height: diameter * 0.8 // Reduce size (e.g., 70% of original)
    })
  }

  // -------------------------------------------paste the qrCode in the pdf--------------------------------------

  const paperContent = `
    ECOLE SUPERIEURE POLYTECHNIQUE DE TOAMASINA
    ${jsonData.f1}
    ${jsonData.f2}
    ${jsonData.f3}
    ${jsonData.f4}
    ${jsonData.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 = 4
        const y = 39
        const qrSize = 92

        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 [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_${jsonData.f1}.pdf`)
      })()
    }
  )

  // Serialize the PDF and return the modified document
  const modifiedPdfBytes = await pdfDoc.save()
  return modifiedPdfBytes
}

/**
 * function who export and filled PDF data
 * @param {JSON} jsonData
 */
export const processPdf = async (jsonData) => {
  await fillPdfFields(jsonData)
}