import { Document, Packer, Paragraph, TextRun, AlignmentType, HeadingLevel, ImageRun } from 'docx';
import { saveAs } from 'file-saver';

export const generateProjectDoc = async (
  studentName: string, 
  grade: string, 
  rollNumber: string, 
  projectTitle: string, 
  projectId: string,
  schoolName?: string, 
  principalName?: string,
  docContent?: {
    objective: string;
    conceptsUsed: string;
    howItWorks: string;
    whatILearned: string;
  }
) => {
  const logoUrl = "https://raw.githubusercontent.com/RS-Learning-Lab/assets/main/logo.png";
  let logoImage;
  try {
    const response = await fetch(logoUrl);
    const buffer = await response.arrayBuffer();
    logoImage = new ImageRun({
      data: new Uint8Array(buffer),
      transformation: {
        width: 100,
        height: 100,
      },
    } as any);
  } catch (error) {
    console.error("Failed to load logo for document:", error);
  }

  const doc = new Document({
    sections: [
      {
        properties: {},
        children: [
          // Front Page Logo
          ...(logoImage ? [
            new Paragraph({
              alignment: AlignmentType.CENTER,
              children: [logoImage],
            }),
            new Paragraph({ spacing: { before: 200 } }),
          ] : []),
          
          // Front Page
          new Paragraph({
            alignment: AlignmentType.CENTER,
            children: [
              new TextRun({
                text: "RS LEARNING LAB",
                bold: true,
                size: 56,
                color: "0b8c9f",
                font: "Calibri",
              }),
            ],
          }),
          new Paragraph({ spacing: { before: 200 } }),
          new Paragraph({
            alignment: AlignmentType.CENTER,
            children: [
              new TextRun({
                text: "Innovation through Code",
                italics: true,
                size: 24,
                color: "666666",
              }),
            ],
          }),
          new Paragraph({ spacing: { before: 1200 } }),
          new Paragraph({
            alignment: AlignmentType.CENTER,
            children: [
              new TextRun({
                text: "PROJECT DOCUMENTATION",
                bold: true,
                size: 40,
                underline: {},
              }),
            ],
          }),
          new Paragraph({ spacing: { before: 800 } }),
          new Paragraph({
            alignment: AlignmentType.CENTER,
            children: [
              new TextRun({
                text: projectTitle.toUpperCase(),
                bold: true,
                size: 32,
                color: "333333",
              }),
            ],
          }),
          new Paragraph({ spacing: { before: 1200 } }),
          
          // Front Page Details (Centered)
          new Paragraph({
            alignment: AlignmentType.CENTER,
            children: [
              new TextRun({ text: "Project ID: ", bold: true, size: 24 }),
              new TextRun({ text: `RS-PROJ-${projectId}`, size: 24 }),
            ],
          }),
          new Paragraph({ spacing: { before: 200 } }),
          new Paragraph({
            alignment: AlignmentType.CENTER,
            children: [
              new TextRun({ text: "Student Name: ", bold: true, size: 24 }),
              new TextRun({ text: studentName, size: 24 }),
            ],
          }),
          new Paragraph({ spacing: { before: 200 } }),
          new Paragraph({
            alignment: AlignmentType.CENTER,
            children: [
              new TextRun({ text: "Class: ", bold: true, size: 24 }),
              new TextRun({ text: grade, size: 24 }),
            ],
          }),
          new Paragraph({ spacing: { before: 200 } }),
          new Paragraph({
            alignment: AlignmentType.CENTER,
            children: [
              new TextRun({ text: "School Name: ", bold: true, size: 24 }),
              new TextRun({ text: schoolName || "N/A", size: 24 }),
            ],
          }),
          new Paragraph({ spacing: { before: 200 } }),
          new Paragraph({
            alignment: AlignmentType.CENTER,
            children: [
              new TextRun({ text: "Founder Name: ", bold: true, size: 24 }),
              new TextRun({ text: "Gokula Krishnan", size: 24 }),
            ],
          }),
          new Paragraph({ spacing: { before: 200 } }),
          new Paragraph({
            alignment: AlignmentType.CENTER,
            children: [
              new TextRun({ text: "Date: ", bold: true, size: 24 }),
              new TextRun({ text: new Date().toLocaleDateString(), size: 24 }),
            ],
          }),

          // Page Break
          new Paragraph({ children: [new TextRun({ text: "", break: 1 })] }),

          // Acknowledgement Page
          new Paragraph({
            alignment: AlignmentType.CENTER,
            children: [
              new TextRun({ text: "ACKNOWLEDGEMENT", bold: true, size: 36, color: "0b8c9f" }),
            ],
          }),
          new Paragraph({ spacing: { before: 800 } }),
          new Paragraph({
            alignment: AlignmentType.JUSTIFIED,
            children: [
              new TextRun({
                text: "I would like to extend my heartfelt gratitude to my school for their unwavering support and for providing the necessary resources to undertake this project. I am particularly grateful to RS Learning Lab and my mentor, Mr. Gokula Krishnan, for his exceptional guidance, technical expertise, and constant encouragement throughout the project's lifecycle. His mentorship has been instrumental in the successful completion of this endeavor. Furthermore, I would like to express my sincere appreciation to my parents and friends for their continuous motivation and support, which played a vital role in my academic journey.",
                size: 24,
              }),
            ],
          }),
          new Paragraph({ spacing: { before: 1200 } }),
          new Paragraph({
            alignment: AlignmentType.RIGHT,
            children: [
              new TextRun({ text: "__________________________", bold: true }),
            ],
          }),
          new Paragraph({
            alignment: AlignmentType.RIGHT,
            children: [
              new TextRun({ text: "Student Signature", size: 18, color: "666666" }),
            ],
          }),

          // Page Break
          new Paragraph({ children: [new TextRun({ text: "", break: 1 })] }),

          // Certificate
          new Paragraph({
            alignment: AlignmentType.CENTER,
            children: [
              new TextRun({ text: "CERTIFICATE OF COMPLETION", bold: true, size: 36, color: "0b8c9f" }),
            ],
          }),
          new Paragraph({ spacing: { before: 600 } }),
          new Paragraph({
            alignment: AlignmentType.JUSTIFIED,
            children: [
              new TextRun({
                text: `This is to formally certify that `,
                size: 24,
              }),
              new TextRun({
                text: studentName,
                bold: true,
                size: 24,
              }),
              new TextRun({
                text: ` of `,
                size: 24,
              }),
              new TextRun({
                text: grade,
                bold: true,
                size: 24,
              }),
              new TextRun({
                text: `, `,
                size: 24,
              }),
              new TextRun({
                text: schoolName || "N/A",
                bold: true,
                size: 24,
              }),
              new TextRun({
                text: ` has successfully designed, developed, and documented the project titled `,
                size: 24,
              }),
              new TextRun({
                text: `"${projectTitle}"`,
                bold: true,
                size: 24,
              }),
              new TextRun({
                text: `. This project was completed as part of the curriculum at RS Learning Lab, demonstrating proficiency in logical reasoning and technical implementation.`,
                size: 24,
              }),
            ],
          }),
          new Paragraph({ spacing: { before: 1600 } }),
          
          // Signatures
          new Paragraph({
            alignment: AlignmentType.LEFT,
            children: [
              new TextRun({ text: "__________________________", bold: true }),
              new TextRun({ text: "\t\t\t\t\t__________________________", bold: true }),
            ],
          }),
          new Paragraph({
            alignment: AlignmentType.LEFT,
            children: [
              new TextRun({ text: "Gokula Krishnan", bold: true, size: 22 }),
              new TextRun({ text: "\t\t\t\t\t", bold: true, size: 22 }),
            ],
          }),
          new Paragraph({
            alignment: AlignmentType.LEFT,
            children: [
              new TextRun({ text: "Founder, RS Learning Lab", size: 18, color: "666666" }),
              new TextRun({ text: "\t\t\t\t\tSchool Signature", size: 18, color: "666666" }),
            ],
          }),

          // Page Break
          new Paragraph({ children: [new TextRun({ text: "", break: 1 })] }),

          // Project Technical Content
          new Paragraph({
            alignment: AlignmentType.LEFT,
            children: [
              new TextRun({ text: "PROJECT CONTENT", bold: true, size: 36, color: "0b8c9f" }),
            ],
          }),
          new Paragraph({ spacing: { before: 600 } }),
          
          new Paragraph({
            children: [new TextRun({ text: "1. Objective", bold: true, size: 28 })],
          }),
          new Paragraph({ spacing: { before: 200 } }),
          new Paragraph({
            alignment: AlignmentType.JUSTIFIED,
            children: [
              new TextRun({ 
                text: docContent?.objective || "The primary objective of this project is to develop a functional application that demonstrates the practical application of programming logic in a real-world context.", 
                size: 22,
                color: "444444"
              }),
            ],
          }),

          new Paragraph({ spacing: { before: 400 } }),
          new Paragraph({
            children: [new TextRun({ text: "2. Concepts Used", bold: true, size: 28 })],
          }),
          new Paragraph({ spacing: { before: 200 } }),
          new Paragraph({
            alignment: AlignmentType.JUSTIFIED,
            children: [
              new TextRun({ 
                text: docContent?.conceptsUsed || "Core logic, variables, and algorithmic thinking were applied to build this solution.", 
                size: 22,
                color: "444444"
              }),
            ],
          }),

          new Paragraph({ spacing: { before: 400 } }),
          new Paragraph({
            children: [new TextRun({ text: "3. How It Works", bold: true, size: 28 })],
          }),
          new Paragraph({ spacing: { before: 200 } }),
          new Paragraph({
            alignment: AlignmentType.JUSTIFIED,
            children: [
              new TextRun({ 
                text: docContent?.howItWorks || "The implementation follows a structured approach to process input and generate the desired output.", 
                size: 22,
                color: "444444"
              }),
            ],
          }),

          new Paragraph({ spacing: { before: 400 } }),
          new Paragraph({
            children: [new TextRun({ text: "4. What I Learned", bold: true, size: 28 })],
          }),
          new Paragraph({ spacing: { before: 200 } }),
          new Paragraph({
            alignment: AlignmentType.JUSTIFIED,
            children: [
              new TextRun({ 
                text: docContent?.whatILearned || "Through this project, I have gained significant insights into problem-solving and technical implementation.", 
                size: 22,
                color: "444444"
              }),
            ],
          }),

          new Paragraph({ spacing: { before: 1200 } }),

          // Declaration
          new Paragraph({
            alignment: AlignmentType.CENTER,
            children: [
              new TextRun({
                text: "DECLARATION",
                bold: true,
                size: 24,
                color: "333333",
              }),
            ],
          }),
          new Paragraph({ spacing: { before: 200 } }),
          new Paragraph({
            alignment: AlignmentType.CENTER,
            children: [
              new TextRun({
                text: "I hereby declare that this project is a result of my own efforts and has been completed with integrity under the academic guidance of RS Learning Lab. This is my own work.",
                italics: true,
                size: 20,
                color: "666666",
              }),
            ],
          }),
          new Paragraph({ spacing: { before: 1200 } }),

          // Evaluation Section
          new Paragraph({
            alignment: AlignmentType.LEFT,
            children: [
              new TextRun({ text: "OFFICIAL EVALUATION", bold: true, size: 24, color: "0b8c9f" }),
            ],
          }),
          new Paragraph({ spacing: { before: 400 } }),
          new Paragraph({
            alignment: AlignmentType.LEFT,
            children: [
              new TextRun({ text: "Performance Score: ", bold: true, size: 22 }),
              new TextRun({ text: "__________ / 100", size: 22 }),
            ],
          }),
          new Paragraph({ spacing: { before: 400 } }),
          new Paragraph({
            alignment: AlignmentType.LEFT,
            children: [
              new TextRun({ text: "Instructor Remarks: ", bold: true, size: 22 }),
            ],
          }),
          new Paragraph({
            alignment: AlignmentType.LEFT,
            children: [
              new TextRun({ text: "__________________________________________________________________________", size: 18, color: "999999" }),
            ],
          }),
        ],
      },
    ],
  });

  const blob = await Packer.toBlob(doc);
  saveAs(blob, `${projectTitle.replace(/\s+/g, '_')}_Documentation.docx`);
};
