import { Body, Controller, Get, Post, Query, Res } from "@nestjs/common";
import { Response } from "express";
import { InventoryService } from "./inventory.service";
import * as PDFDocument from "pdfkit";

@Controller("inventory")
export class InventoryController {
  constructor(private readonly inventoryService: InventoryService) {}

  @Get()
  getInventory() {
    return this.inventoryService.getInventory();
  }

  @Get("summary")
  getSummary() {
    return this.inventoryService.getSummary();
  }

  @Get("expiry")
  getExpiry(
    @Query("months") months?: string,
    @Query("warehouses") warehouses?: string,
  ) {
    const warehouseNames = warehouses
      ? warehouses.split(",").map((w) => w.trim()).filter(Boolean)
      : undefined;
    return this.inventoryService.getExpiry(months ? Number(months) : 6, warehouseNames);
  }

  @Post("expiry/report")
  async generateExpiryReport(
    @Body()
    body: {
      warehouses?: string[];
      items?: string[];
      months?: number;
      downloadedBy: string;
      reviewedBy?: string;
      approvedBy?: string;
    },
    @Res() res: Response,
  ) {
    const rows = await this.inventoryService.getExpiry(
      body.months ?? 6,
      body.warehouses?.length ? body.warehouses : undefined,
    );

    // Filter by items if specified
    const filtered = body.items?.length
      ? rows.filter((r) => body.items!.some((i) => i.toLowerCase() === (r.itemName ?? "").toLowerCase()))
      : rows;

    const today = new Date().toLocaleDateString("en-AE", {
      day: "2-digit", month: "long", year: "numeric",
    });

    const MARGIN = 50;
    const PAGE_WIDTH = 595;
    const PAGE_HEIGHT = 842;
    const CONTENT_BOTTOM = PAGE_HEIGHT - 100; // leave 100pt for footer

    const buffer = await new Promise<Buffer>((resolve, reject) => {
      const doc = new PDFDocument({ margin: MARGIN, size: "A4", autoFirstPage: true });
      const chunks: Buffer[] = [];
      doc.on("data", (c: Buffer) => chunks.push(c));
      doc.on("end", () => resolve(Buffer.concat(chunks)));
      doc.on("error", reject);

      const drawHeader = () => {
        doc.fontSize(16).font("Helvetica-Bold").fillColor("#1f2740")
          .text("ROYAL HORIZON GENERAL TRADING LLC", MARGIN, MARGIN, { align: "center", width: PAGE_WIDTH - MARGIN * 2 });
        doc.fontSize(11).font("Helvetica").fillColor("#1f2740")
          .text("Expiry Report", { align: "center" });
        doc.fontSize(9).fillColor("#79839a")
          .text(`Generated: ${today}`, { align: "center" });
        doc.moveDown(0.5);
        doc.moveTo(MARGIN, doc.y).lineTo(PAGE_WIDTH - MARGIN, doc.y).strokeColor("#dfe5f0").stroke();
        doc.moveDown(0.5);

        // Table column headers
        const cols = { item: MARGIN, batch: 190, expiry: 300, warehouse: 380, mt: 500 };
        const headerY = doc.y;
        doc.fillColor("#79839a").fontSize(8).font("Helvetica-Bold");
        doc.text("ITEM", cols.item, headerY, { width: 130 });
        doc.text("BATCH", cols.batch, headerY, { width: 100 });
        doc.text("EXPIRY DATE", cols.expiry, headerY, { width: 70 });
        doc.text("WAREHOUSE", cols.warehouse, headerY, { width: 110 });
        doc.text("AVAIL. MT", cols.mt, headerY, { width: 60 });
        doc.moveDown(0.4);
        doc.moveTo(MARGIN, doc.y).lineTo(PAGE_WIDTH - MARGIN, doc.y).strokeColor("#dfe5f0").stroke();
        doc.moveDown(0.3);
      };

      const drawFooter = () => {
        const footerY = doc.page.height - 70;
        doc.moveTo(MARGIN, footerY).lineTo(PAGE_WIDTH - MARGIN, footerY).strokeColor("#dfe5f0").stroke();
        doc.fillColor("#1f2740").fontSize(9).font("Helvetica-Bold");
        doc.text("Downloaded By:", MARGIN, footerY + 10);
        doc.text("Reviewed By:", 210, footerY + 10);
        doc.text("Approved By:", 380, footerY + 10);
        doc.font("Helvetica").fillColor("#79839a");
        doc.text(body.downloadedBy || "_______________", MARGIN, footerY + 24);
        doc.text(body.reviewedBy || "_______________", 210, footerY + 24);
        doc.text(body.approvedBy || "_______________", 380, footerY + 24);
      };

      // Draw header on first page
      drawHeader();

      const cols = { item: MARGIN, batch: 190, expiry: 300, warehouse: 380, mt: 500 };

      for (const row of filtered) {
        // Check if we need a new page (leave room for footer)
        if (doc.y > CONTENT_BOTTOM) {
          doc.addPage();
          drawHeader();
        }

        const days = row.expiryDate
          ? Math.ceil((new Date(row.expiryDate).getTime() - Date.now()) / 86400000)
          : null;
        const isExpired = days !== null && days <= 0;
        const textColor = isExpired ? "#d64545" : "#1f2740";

        // Truncate warehouse string — show first 2 + count
        const whList = (row.warehouse ?? "").split(", ").filter(Boolean);
        const whDisplay = whList.length <= 2
          ? whList.join(", ")
          : `${whList.slice(0, 2).join(", ")} +${whList.length - 2}`;

        // Truncate item name to fit column
        const itemDisplay = (row.itemName ?? "—").length > 22
          ? (row.itemName ?? "—").slice(0, 20) + "…"
          : (row.itemName ?? "—");

        const ROW_HEIGHT = 14;
        const rowY = doc.y;

        doc.fillColor(textColor).fontSize(9).font("Helvetica");
        doc.text(itemDisplay,              cols.item,      rowY, { width: 130, lineBreak: false });
        doc.text(row.batchNumber ?? "—",   cols.batch,     rowY, { width: 100, lineBreak: false });
        doc.text(row.expiryDate ?? "—",    cols.expiry,    rowY, { width: 70,  lineBreak: false });
        doc.text(whDisplay,                cols.warehouse, rowY, { width: 110, lineBreak: false });
        doc.text(`${row.availableMt} MT`,  cols.mt,        rowY, { width: 60,  lineBreak: false });

        doc.y = rowY + ROW_HEIGHT;
        doc.moveTo(MARGIN, doc.y).lineTo(PAGE_WIDTH - MARGIN, doc.y).strokeColor("#f0f4fa").stroke();
        doc.y = doc.y + 3;
      }

      // Draw footer only once on the last page
      drawFooter();

      doc.end();
    });

    const fileName = `expiry-report-${Date.now()}.pdf`;
    res.set({
      "Content-Type": "application/pdf",
      "Content-Disposition": `attachment; filename="${fileName}"`,
      "Content-Length": buffer.length,
    });
    res.end(buffer);
  }
}
