import { PDFDocument } from 'pdf-lib'
import { saveAs } from 'file-saver'
import PDF from '../../assets/autorisationstage.pdf'
import dayjs from 'dayjs'

const PDFEditorStage = async (data) => {
  const existingPdfBytes = await fetch(PDF).then((res) => res.arrayBuffer())

  const fullDate = dayjs().format('YYYY-MM-DD')

  // Load the existing PDF
  const pdfDoc = await PDFDocument.load(existingPdfBytes)

  // Get the form fields and fill them
  const form = pdfDoc.getForm()
  form.getTextField('f1').setText(data.f1)
  form.getTextField('f2').setText(data.f1)

  // Save the modified PDF
  const pdfBytes = await pdfDoc.save()

  // Trigger the download
  const blob = new Blob([pdfBytes], { type: 'application/pdf' })
  saveAs(blob, `autorisation_stage${fullDate}.pdf`)
}

export default PDFEditorStage
