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 generateFilledKarbahiForm(formData: KarbahiFormData): Promise<Buffer> {
  try {
    // Read the existing PDF template
    const templatePath = './public/templates/awasyek-karbahi-gari-pau-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, 506, 38);
    drawText(firstPage, NepaliDay, 532, 38);

    //subject
    drawText(firstPage, formData.subject, 173, 88);

    // Original ID/URL field
    drawText(firstPage, formData.caseDetails.originalID_URL, 219, 193);

    // Incident Type checkboxes
    drawCheckbox(firstPage, formData.caseDetails.incidentType.mediaContent, 169, 211);
    drawCheckbox(firstPage, formData.caseDetails.incidentType.financialTransaction, 319, 211);
    drawCheckbox(firstPage, formData.caseDetails.incidentType.unauthorizedAccess, 414, 211);

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

    const isTikTok = socialMediaPlatform.includes('TikTok');

    drawCheckbox(firstPage, isFBMessenger, 189, 231);
    drawCheckbox(firstPage, isTikTok, 369, 234);

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

    // Fraudster ID/URL field
    drawText(firstPage, formData.caseDetails.fraudsterID_URL, 257, 256);

    // Incident description
    const description = formData.caseDetails.incidentDescription || '';
    const suspectDetails = formData.caseDetails.suspectDetails || '';

    const wrappedDescription = wrapTextWithNepali(description, 100); // Character count per line
    let descY = 289; // Starting Y position
    const descX = 60; // Starting X position

    // Draw each line of the description with proper spacing
    const lineSpacing = 17; // Adjust for proper line spacing
    wrappedDescription.forEach((line, index) => {
      if (index < 15) {
        // Limit to prevent overflow
        drawText(firstPage, line, descX, descY + index * lineSpacing, 10);
      }
    });

    const wrappedDescriptionOfSuspect = wrapTextWithNepali(suspectDetails, 100); // Character count per line
    let descxY = 463; // Starting Y position
    const descxX = 60; // Starting X position

    // Draw each line of the description with proper spacing
    const linespacing = 17; // Adjust for proper line spacing
    wrappedDescriptionOfSuspect.forEach((line, index) => {
      if (index < 15) {
        // Limit to prevent overflow
        drawText(firstPage, line, descxX, descxY + index * linespacing, 10);
      }
    });

    // Checkboxes for attached documents
    const attachedDocs = formData.caseDetails.attachedDocuments || {
      screenshots: false,
      citizenshipCopy: false,
      passport: false,
      nationalIDCard: false,
      employeeOrStudentID: false,
      otherDocument: '',
    };

    // Citizenship copy checkbox
    drawCheckbox(firstPage, attachedDocs.citizenshipCopy, 183, 543);

    // Passport checkbox
    drawCheckbox(firstPage, attachedDocs.passport, 295, 543);

    // National ID card checkbox
    drawCheckbox(firstPage, attachedDocs.nationalIDCard, 397, 543);

    // Employee or student ID checkbox
    drawCheckbox(firstPage, attachedDocs.employeeOrStudentID, 184, 569);

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

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

    // Name field
    drawText(firstPage, complainant.name, 103, 661);

    // Date of birth field
    drawText(firstPage, complainant.dateOfBirth, 121, 687);

    // Address field
    drawText(firstPage, complainant.address, 105, 712);

    // ID number field
    drawText(firstPage, complainant.idNumber, 428, 668);

    // Contact number field
    drawText(firstPage, complainant.contactNumber, 422, 695);

    // Guardian contact number field
    drawText(firstPage, complainant.guardianContactNumber, 438, 719);

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

function wrapTextWithNepali(text: string, maxChars: number): string[] {
  if (!text) return [''];
  const words = text.split(' ');
  const lines: string[] = [];
  let currentLine = '';

  words.forEach(word => {
    if ((currentLine + word).length <= maxChars) {
      currentLine += word + ' ';
    } else {
      lines.push(currentLine.trim());
      currentLine = word + ' ';
    }
  });
  if (currentLine.trim()) {
    lines.push(currentLine.trim());
  }
  return lines;
}
