import { PDFDocument, PDFPage, rgb, StandardFonts } from 'pdf-lib';
import fontkit from '@pdf-lib/fontkit';
import 'regenerator-runtime/runtime';
import fs from 'fs';

import NepaliDate from 'nepali-datetime';

const nepaliDate = new NepaliDate();
const NepaliMonth = (nepaliDate.getMonth() + 1).toString();
const NepaliDay = nepaliDate.getDate().toString();

export async function generateFilledFakeOrHackedForm(formData: FakeOrHackedFormData): Promise<Buffer> {
  try {
    // Read the existing PDF template
    const templatePath = './public/templates/fake-or-hacked-ccb-2082.pdf';
    const existingPdfBytes = fs.readFileSync(templatePath);

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

    // Register fontkit with the PDF document
    pdfDoc.registerFontkit(fontkit);

    // Get the pages
    const pages = pdfDoc.getPages();
    const firstPage = pages[0];

    // Create a helper function for Devanagari text support
    const formatText = (text: string | number | undefined): string => {
      if (text === undefined || text === null) return '';
      return text.toString();
    };

    // For Nepali text support:
    const nepaliFontBytes = fs.readFileSync('./public/fonts/nepali.ttf');
    const font = await pdfDoc.embedFont(nepaliFontBytes);

    // Standard font for English text (optional)
    const standardFont = await pdfDoc.embedFont(StandardFonts.Helvetica);

    const drawText = (page: PDFPage, text: string, x: number, y: number, fontSize: number = 10, useNepaliFonts: boolean = true) => {
      page.drawText(formatText(text), {
        x,
        y: page.getHeight() - y, // PDF coordinates start from bottom left
        size: fontSize,
        font: useNepaliFonts ? font : standardFont,
        color: rgb(0, 0, 0),
      });
    };

    // Helper function to draw checkbox
    const drawCheckbox = (page: PDFPage, isChecked: boolean | undefined, x: number, y: number) => {
      if (isChecked) {
        // Convert y coordinate to PDF coordinates (from top-left to bottom-left origin)
        const pdfY = page.getHeight() - y;

        // Draw a small checkmark using lines
        page.drawLine({
          start: { x: x - 2, y: pdfY - 2 },
          end: { x: x, y: pdfY - 4 },
          thickness: 2,
          color: rgb(0, 0, 0),
        });

        page.drawLine({
          start: { x: x, y: pdfY - 4 },
          end: { x: x + 4, y: pdfY + 2 },
          thickness: 1,
          color: rgb(0, 0, 0),
        });
      }
    };

    // Fill in the date fields (upper right)
    drawText(firstPage, NepaliMonth, 472, 46);
    drawText(firstPage, NepaliDay, 500, 46);

    // Social media platform checkboxes
    const socialMediaPlatform = formData.socialMediaPlatform || '';
    const isFBMessenger =
      socialMediaPlatform.includes('Facebook') ||
      socialMediaPlatform.includes('Messenger') ||
      socialMediaPlatform.includes('Instagram') ||
      socialMediaPlatform.includes('WhatsApp');
    const isTikTok = socialMediaPlatform.includes('TikTok');

    drawCheckbox(firstPage, isFBMessenger, 144, 126);
    drawCheckbox(firstPage, isTikTok, 330, 126);

    // If other platform, write it in
    if (!isFBMessenger && !isTikTok && socialMediaPlatform) {
      drawText(firstPage, socialMediaPlatform, 430, 126);
    }

    // Incident type checkboxes
    drawCheckbox(firstPage, formData.incidentType.hackedID, 150, 152);
    drawCheckbox(firstPage, formData.incidentType.fakeID, 241, 152);

    // Additional details checkboxes
    drawCheckbox(firstPage, formData.additionalDetails.mediaContent, 111, 177);
    drawCheckbox(firstPage, formData.additionalDetails.financialTransaction, 272, 177);
    if (formData.additionalDetails.other) {
      drawText(firstPage, formData.additionalDetails.other, 423, 177);
    }

    // Account Details section
    const accountDetails = formData.accountDetails || {
      fakeOrHackedURL: '',
      profileFullName: '',
      languageUsed: {
        english: false,
        nepali: false,
        other: '',
      },
      hackDate: '',
      previousPhoneNumber: '',
      previousEmail: '',
      deviceDetails: '',
      idCreationDate: {
        isAD: false,
        isBS: false,
        date: '',
      },
      currentProfileURL: '',
      unusedEmail: '',
    };

    // Fake/Hacked ID URL
    drawText(firstPage, accountDetails.fakeOrHackedURL, 171, 240);

    // Profile full name
    drawText(firstPage, accountDetails.profileFullName, 242, 266);

    // Language used checkboxes
    drawCheckbox(firstPage, accountDetails.languageUsed.english, 179, 292);
    drawCheckbox(firstPage, accountDetails.languageUsed.nepali, 218, 292);
    if (accountDetails.languageUsed.other) {
      // Other language
      drawText(firstPage, accountDetails.languageUsed.other, 297, 294);
    }

    // Hack date
    drawText(firstPage, accountDetails.hackDate, 443, 292);

    // Previous phone number
    drawText(firstPage, accountDetails.previousPhoneNumber, 208, 322);

    // Previous email
    drawText(firstPage, accountDetails.previousEmail, 379, 322);

    // Device details (brand and model)
    drawText(firstPage, accountDetails.deviceDetails, 393, 347);

    // ID creation date
    drawCheckbox(firstPage, accountDetails.idCreationDate.isAD, 176, 376);
    drawCheckbox(firstPage, accountDetails.idCreationDate.isBS, 216, 376);
    drawText(firstPage, accountDetails.idCreationDate.date, 248, 376);

    // Current profile URL
    drawText(firstPage, accountDetails.currentProfileURL, 239, 405);

    // Unused email
    drawText(firstPage, accountDetails.unusedEmail, 210, 430);

    // Attached documents checkboxes
    const attachedDocs = formData.attachedDocuments || {
      screenshots: false,
      citizenshipCopy: false,
      passport: false,
      nationalIDCard: false,
      employeeOrStudentID: false,
      otherDocument: '',
    };

    // Citizenship copy checkbox
    drawCheckbox(firstPage, attachedDocs.citizenshipCopy, 49, 523);

    // Passport checkbox
    drawCheckbox(firstPage, attachedDocs.passport, 159, 523);

    // National ID card checkbox
    drawCheckbox(firstPage, attachedDocs.nationalIDCard, 263, 523);

    // Employee or student ID checkbox
    drawCheckbox(firstPage, attachedDocs.employeeOrStudentID, 48, 550);

    // Other document field
    if (attachedDocs.otherDocument) {
      drawText(firstPage, attachedDocs.otherDocument, 311, 552);
    }

    // Complainant details
    const complainant = formData.complainant || {
      name: '',
      dateOfBirth: '',
      address: '',
      idNumber: '',
      contactNumber: '',
      guardianContactNumber: '',
    };

    // Name field
    drawText(firstPage, complainant.name, 101, 650);

    // Date of birth field
    drawText(firstPage, complainant.dateOfBirth, 117, 675);

    // Address field
    drawText(firstPage, complainant.address, 98, 697);

    // ID number field
    drawText(firstPage, complainant.idNumber, 417, 649);

    // Contact number field
    drawText(firstPage, complainant.contactNumber, 411, 675);

    // Guardian contact number field
    drawText(firstPage, complainant.guardianContactNumber, 426, 701);

    // Admin details for page hack/admin access revoke
    if (formData.adminDetails) {
      drawText(firstPage, formData.adminDetails, 40, 748);
    }

    // Save the PDF
    const pdfBytes = await pdfDoc.save();
    return Buffer.from(pdfBytes);
  } catch (error) {
    console.error('Error generating filled form:', error);
    throw error;
  }
}

// Example usage:
/*
const sampleData: FakeOrHackedFormData = {
  complaintDate: {
    year: "2082",
    month: "01",
    day: "15"
  },
  socialMediaPlatform: "FB/Messenger",
  incidentType: {
    hackedID: true,
    fakeID: false
  },
  additionalDetails: {
    mediaContent: true,
    financialTransaction: false,
    other: ""
  },
  attachedDocuments: {
    screenshots: true,
    citizenshipCopy: true,
    passport: false,
    nationalIDCard: false,
    employeeOrStudentID: false,
    otherDocument: ""
  },
  complainant: {
    name: "सन्तोष दाहाल",
    dateOfBirth: "2045/03/15",
    address: "काठमाडौँ महानगरपालिका-३२, काठमाडौँ",
    idNumber: "01-01-74-03458",
    contactNumber: "9841XXXXXX",
    guardianContactNumber: "9851XXXXXX"
  },
  adminDetails: "Page admin: admin@example.com, Phone: 98XXXXXXXX",
  accountDetails: {
    fakeOrHackedURL: "https://facebook.com/hacked.profile",
    profileFullName: "सन्तोष दाहाल",
    languageUsed: {
      english: false,
      nepali: true,
      other: ""
    },
    hackDate: "२०८२/०१/०१",
    previousPhoneNumber: "9841XXXXXX",
    previousEmail: "original@example.com",
    deviceDetails: "Samsung Galaxy S21",
    idCreationDate: {
      isAD: false,
      isBS: true,
      date: "२०७५/०८/१०"
    },
    currentProfileURL: "https://facebook.com/new.profile",
    unusedEmail: "unused@example.com"
  }
};
*/
