import { PDFDocument, rgb, StandardFonts } from 'pdf-lib'

export const generatePDF = async (students) => {
  // Sort by NomPrenom alphabetically
  const sortedStudents = students.sort((a, b) => a.nom.localeCompare(b.nom))

  // function compareMention(id) {
  //   let mentionText;
  //   mentions.map((ment) => {
  //     if (id == ment.id) {
  //       mentionText = ment.nom
  //     }
  //   })

  //   return mentionText;
  // }
  const pdfDoc = await PDFDocument.create()
  const pageWidth = 595 // A4 width in points
  const pageHeight = 842 // A4 height in points
  const margin = 40
  const fontSize = 12
  const rowHeight = 25
  const tableStartY = pageHeight - margin - 50
  const maxRowsPerPage = Math.floor((tableStartY - margin) / rowHeight)

  const font = await pdfDoc.embedFont(StandardFonts.Helvetica)
  const page = pdfDoc.addPage([pageWidth, pageHeight])

  let y = tableStartY
  let rowCount = 0

  // Add Table Headers
  page.drawText('Nom matieres', {
    x: pageWidth / 2 - 50,
    y,
    size: 16,
    font,
    color: rgb(0, 0, 0)
  })

  y -= 30

  const headers = ['N°', 'Nom et Prenom', 'Mention', 'Émergement']
  const columnWidths = [50, 200, 100, 100]
  const xPositions = [
    margin,
    margin + columnWidths[0],
    margin + columnWidths[0] + columnWidths[1],
    margin + columnWidths[0] + columnWidths[1] + columnWidths[2]
  ]

  headers.forEach((header, index) => {
    page.drawText(header, { x: xPositions[index], y, size: fontSize, font, color: rgb(0, 0, 0) })
  })

  y -= rowHeight

  // Function to add a new page when needed
  const addNewPage = () => {
    const newPage = pdfDoc.addPage([pageWidth, pageHeight])
    y = tableStartY
    rowCount = 0
    return newPage
  }

  // Loop through student data and populate the table
  sortedStudents.forEach((student, index) => {
    if (rowCount >= maxRowsPerPage) {
      page = addNewPage()
    }

    const rowData = [
      (index + 1).toString(),
      `${student.nom} ${student.prenom}`,
      student.mention,
      ''
    ]

    rowData.forEach((text, i) => {
      page.drawText(text, { x: xPositions[i], y, size: fontSize, font, color: rgb(0, 0, 0) })
    })

    y -= rowHeight
    rowCount++
  })

  // Save and download PDF
  const pdfBytes = await pdfDoc.save()
  const blob = new Blob([pdfBytes], { type: 'application/pdf' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = 'student_list.pdf'
  link.click()
}
