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

const PDFEditorRecepice = 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.f2)
  form.getTextField('f3').setText(data.f3)
  form.getTextField('f4').setText(data.f4)
  form.getTextField('f5').setText(fullDate)
  form.getTextField('f6').setText(data.f6)
  form.getTextField('f7').setText(data.f7)

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

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

export default PDFEditorRecepice
