/**
 * Générateur du devis commercial (distinct de l'étude en lib/pdf.ts).
 *
 * Différence avec l'étude :
 *   - L'étude (lib/pdf.ts) est informative, générée automatiquement à la
 *     soumission du configurateur, avec des phases indicatives.
 *   - Le devis est un document commercial numéroté, avec une date de
 *     validité, généré manuellement depuis le CRM (/admin/leads) quand un
 *     commercial décide d'engager la vente. Le numéro n'est attribué
 *     qu'une seule fois (voir app/api/leads/[id]/devis/route.ts).
 *
 * ⚠️ MENTIONS LÉGALES : les mentions de TVA/facturation ci-dessous sont des
 * placeholders génériques. À adapter obligatoirement selon le statut
 * juridique réel de l'entreprise (auto-entrepreneur, SASU, SARL...) avant
 * tout envoi à un client — ce n'est pas un conseil juridique ou comptable.
 */

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

export interface QuotePdfInput {
  devisNumber: string;
  generatedAt: Date;
  validUntil: Date;
  name: string;
  company?: string;
  email: string;
  phone?: string;
  sector?: string;
  modules: RecommendedModule[];
}

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_TEXT = rgb(0.2, 0.2, 0.2);
const COLOR_MUTED = rgb(0.45, 0.45, 0.45);
const COLOR_LINE = rgb(0.85, 0.85, 0.85);

// ⚠️ À adapter selon le statut juridique réel de l'entreprise émettrice.
const LEGAL_MENTIONS = [
  "Devis valable jusqu'à la date d'expiration indiquée ci-dessus.",
  "Prix exprimés en euros. Mentions de TVA à compléter selon le régime fiscal de l'entreprise (auto-entrepreneur, société...).",
  "Ce devis n'est pas une facture et ne constitue pas un engagement contractuel avant signature du bon pour accord.",
];

class Cursor {
  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(h: number) {
    if (this.y - h < MARGIN) {
      this.page = this.doc.addPage([PAGE_WIDTH, PAGE_HEIGHT]);
      this.y = PAGE_HEIGHT - MARGIN;
    }
  }

  text(str: string, x: number, size: number, font: PDFFont, color = COLOR_TEXT) {
    this.ensureSpace(size + 4);
    this.page.drawText(str, { x, y: this.y, size, font, color });
  }

  line(height = 18) {
    this.y -= height;
  }

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

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

export async function generateQuotePdf(input: QuotePdfInput): Promise<Uint8Array> {
  const { devisNumber, generatedAt, validUntil, name, company, email, phone, sector, modules } = 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 Cursor(doc, page, font, bold);

  // En-tête
  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 - 40, size: 20, font: bold, color: rgb(1, 1, 1) });
  cursor.page.drawText("Devis estimatif", {
    x: MARGIN,
    y: PAGE_HEIGHT - 62,
    size: 12,
    font,
    color: rgb(0.8, 0.85, 0.9),
  });

  const rightX = PAGE_WIDTH - MARGIN - 160;
  cursor.page.drawText(`N° ${devisNumber}`, { x: rightX, y: PAGE_HEIGHT - 40, size: 11, font: bold, color: rgb(1, 1, 1) });
  cursor.page.drawText(`Émis le ${generatedAt.toLocaleDateString("fr-FR")}`, {
    x: rightX,
    y: PAGE_HEIGHT - 56,
    size: 9,
    font,
    color: rgb(0.8, 0.85, 0.9),
  });
  cursor.page.drawText(`Valable jusqu'au ${validUntil.toLocaleDateString("fr-FR")}`, {
    x: rightX,
    y: PAGE_HEIGHT - 70,
    size: 9,
    font,
    color: rgb(0.8, 0.85, 0.9),
  });

  cursor.y = PAGE_HEIGHT - 120;

  // Bloc client
  cursor.text("Destinataire", MARGIN, 10, bold, COLOR_DARK);
  cursor.line(16);
  cursor.text(company ? `${company} — ${name}` : name, MARGIN, 11, font);
  cursor.line(16);
  cursor.text(email, MARGIN, 10, font, COLOR_MUTED);
  cursor.line(14);
  if (phone) {
    cursor.text(phone, MARGIN, 10, font, COLOR_MUTED);
    cursor.line(14);
  }
  if (sector) {
    cursor.text(`Secteur : ${sector}`, MARGIN, 10, font, COLOR_MUTED);
    cursor.line(14);
  }
  cursor.line(10);
  cursor.divider();

  // Tableau des lignes
  const colLabelX = MARGIN;
  const colQtyX = PAGE_WIDTH - MARGIN - 190;
  const colPriceX = PAGE_WIDTH - MARGIN - 120;
  const colTotalX = PAGE_WIDTH - MARGIN - 50;

  cursor.text("Module", colLabelX, 9, bold, COLOR_MUTED);
  cursor.text("Qté", colQtyX, 9, bold, COLOR_MUTED);
  cursor.text("Prix unitaire", colPriceX, 9, bold, COLOR_MUTED);
  cursor.text("Total", colTotalX, 9, bold, COLOR_MUTED);
  cursor.line(16);
  cursor.divider();

  let total = 0;
  for (const mod of modules) {
    cursor.text(mod.label, colLabelX, 10, font);
    cursor.text("1", colQtyX, 10, font);
    cursor.text(`${mod.price.toLocaleString("fr-FR")} €`, colPriceX, 10, font);
    cursor.text(`${mod.price.toLocaleString("fr-FR")} €`, colTotalX, 10, font);
    total += mod.price;
    cursor.line(18);
  }

  cursor.divider();
  cursor.text("Total estimatif", colPriceX, 12, bold, COLOR_DARK);
  cursor.text(`${total.toLocaleString("fr-FR")} €`, colTotalX, 12, bold, COLOR_DARK);
  cursor.line(30);

  // Zone signature
  cursor.divider();
  cursor.text("Bon pour accord", MARGIN, 10, bold, COLOR_DARK);
  cursor.line(20);
  cursor.text("Date, signature et cachet :", MARGIN, 9.5, font, COLOR_MUTED);
  cursor.line(50);

  cursor.divider();
  LEGAL_MENTIONS.forEach((m) => {
    cursor.paragraph(m, 8.5);
    cursor.line(2);
  });

  return doc.save();
}
