import { PDFDocument, StandardFonts, rgb, PDFPage, PDFFont } from "pdf-lib";
import type { RecoResult, RecommendedModule } from "./recommendations";

export interface StudyPdfInput {
  name: string;
  company?: string;
  sector?: string;
  budget: number;
  reco: RecoResult;
  createdAt: Date;
}

const PAGE_WIDTH = 595.28;
const PAGE_HEIGHT = 841.89;
const MARGIN = 50;

const COLOR_DARK = rgb(0.043, 0.106, 0.169);
const COLOR_PRIMARY = rgb(0.133, 0.773, 0.369);
const COLOR_SECONDARY = rgb(0.22, 0.741, 0.973);
const COLOR_TEXT = rgb(0.2, 0.2, 0.2);

class PdfCursor {
  doc: PDFDocument;
  page: PDFPage;
  font: PDFFont;
  bold: PDFFont;
  y: number;

  constructor(doc: PDFDocument, page: PDFPage, font: PDFFont, bold: PDFFont) {
    this.doc = doc;
    this.page = page;
    this.font = font;
    this.bold = bold;
    this.y = PAGE_HEIGHT - MARGIN;
  }

  private ensureSpace(height: number) {
    if (this.y - height < MARGIN) {
      this.page = this.doc.addPage([PAGE_WIDTH, PAGE_HEIGHT]);
      this.y = PAGE_HEIGHT - MARGIN;
    }
  }

  title(text: string, size = 18) {
    this.ensureSpace(size + 12);
    this.page.drawText(text, { x: MARGIN, y: this.y, size, font: this.bold, color: COLOR_DARK });
    this.y -= size + 10;
  }

  subtitle(text: string, size = 13, color = COLOR_DARK) {
    this.ensureSpace(size + 8);
    this.page.drawText(text, { x: MARGIN, y: this.y, size, font: this.bold, color });
    this.y -= size + 8;
  }

  paragraph(text: string, size = 10.5, color = COLOR_TEXT) {
    const maxWidth = PAGE_WIDTH - MARGIN * 2;
    const words = text.split(" ");
    let line = "";
    for (const word of words) {
      const testLine = line ? `${line} ${word}` : word;
      const width = this.font.widthOfTextAtSize(testLine, size);
      if (width > maxWidth) {
        this.ensureSpace(size + 4);
        this.page.drawText(line, { x: MARGIN, y: this.y, size, font: this.font, color });
        this.y -= size + 4;
        line = word;
      } else {
        line = testLine;
      }
    }
    if (line) {
      this.ensureSpace(size + 4);
      this.page.drawText(line, { x: MARGIN, y: this.y, size, font: this.font, color });
      this.y -= size + 4;
    }
  }

  moduleLine(mod: RecommendedModule, size = 10.5) {
    this.ensureSpace(size + 6);
    this.page.drawText(`•  ${mod.label}`, { x: MARGIN + 10, y: this.y, size, font: this.font, color: COLOR_TEXT });
    const priceText = `${mod.price.toLocaleString("fr-FR")} €`;
    const priceWidth = this.font.widthOfTextAtSize(priceText, size);
    this.page.drawText(priceText, {
      x: PAGE_WIDTH - MARGIN - priceWidth,
      y: this.y,
      size,
      font: this.font,
      color: COLOR_DARK,
    });
    this.y -= size + 6;
  }

  spacer(height = 12) {
    this.y -= height;
  }

  divider() {
    this.ensureSpace(16);
    this.page.drawLine({
      start: { x: MARGIN, y: this.y },
      end: { x: PAGE_WIDTH - MARGIN, y: this.y },
      thickness: 0.5,
      color: rgb(0.85, 0.85, 0.85),
    });
    this.y -= 16;
  }
}

export async function generateStudyPdf(input: StudyPdfInput): Promise<Uint8Array> {
  const { name, company, sector, budget, reco, createdAt } = input;

  const doc = await PDFDocument.create();
  const page = doc.addPage([PAGE_WIDTH, PAGE_HEIGHT]);
  const font = await doc.embedFont(StandardFonts.Helvetica);
  const bold = await doc.embedFont(StandardFonts.HelveticaBold);
  const cursor = new PdfCursor(doc, page, font, bold);

  cursor.page.drawRectangle({ x: 0, y: PAGE_HEIGHT - 90, width: PAGE_WIDTH, height: 90, color: COLOR_DARK });
  cursor.page.drawText("AZELIOR", { x: MARGIN, y: PAGE_HEIGHT - 45, size: 20, font: bold, color: rgb(1, 1, 1) });
  cursor.page.drawText("Étude personnalisée de votre plateforme", {
    x: MARGIN,
    y: PAGE_HEIGHT - 65,
    size: 11,
    font,
    color: rgb(0.8, 0.85, 0.9),
  });
  cursor.y = PAGE_HEIGHT - 120;

  cursor.title(`Bonjour ${name.split(" ")[0]},`, 15);
  cursor.paragraph(
    `Voici l'étude générée le ${createdAt.toLocaleDateString("fr-FR")} pour ${
      company ? company : "votre projet"
    }${sector ? `, secteur « ${sector} »` : ""}, pour un budget indiqué de ${budget.toLocaleString("fr-FR")} €.`
  );
  cursor.spacer(10);
  cursor.divider();

  cursor.subtitle("Aperçu de votre future plateforme");
  cursor.paragraph(
    `Budget utilisé : ${reco.usedBudget.toLocaleString("fr-FR")} €  •  ` +
      `Budget restant : ${reco.remainingBudget.toLocaleString("fr-FR")} €  •  ` +
      `Délai estimé : ${reco.timeWeeksMin} à ${reco.timeWeeksMax} semaines`
  );
  cursor.paragraph(
    `Automatisation estimée : ${reco.automationPotential}%  •  ` +
      `Temps économisé : ${reco.hoursSavedPerWeek} h / semaine  •  ` +
      `ROI estimé : ${reco.roiMonths} mois  •  Complexité : ${reco.complexity}`
  );
  cursor.spacer(10);
  cursor.divider();

  cursor.subtitle("Modules recommandés", 13, COLOR_PRIMARY);
  if (reco.recommended.length === 0) {
    cursor.paragraph("Aucun module ne rentre dans le budget indiqué pour l'instant.");
  } else {
    reco.recommended.forEach((m) => cursor.moduleLine(m));
  }
  cursor.spacer(10);

  if (reco.reserve.length > 0) {
    cursor.subtitle("Modules en réserve — prochaine évolution", 13, COLOR_SECONDARY);
    reco.reserve.forEach((m) => cursor.moduleLine(m));
    cursor.spacer(10);
  }

  cursor.divider();
  cursor.paragraph(
    "Cette étude est une première estimation automatique, non contractuelle. " +
      "Un conseiller Azelior vous recontacte sous 24 à 48h pour affiner ce projet avec vous."
  );

  return doc.save();
}
