import ExcelJS from "exceljs";
import type { Response } from "express";

export interface PurchaseExportRow {
  lotNo: string;
  supplier: string;
  vegetable: string;
  quantityKg: number | string;
  bags: number | string;
  weightPerBagKg: number | string;
  remainingQuantityKg: number | string;
  remainingBags: number | string;
  ratePerUnit: number | string;
  grandTotal: number | string;
  costPerKg: number | string;
  advanceAmount: number | string;
  balanceAmount: number | string;
}

const COLUMNS: { header: string; key: keyof PurchaseExportRow; width: number }[] =
  [
    { header: "Lot No", key: "lotNo", width: 16 },
    { header: "Supplier", key: "supplier", width: 22 },
    { header: "Vegetable", key: "vegetable", width: 20 },
    { header: "Quantity (KG)", key: "quantityKg", width: 14 },
    { header: "Bags", key: "bags", width: 10 },
    { header: "Weight/Bag (KG)", key: "weightPerBagKg", width: 16 },
    { header: "Remaining Stock (KG)", key: "remainingQuantityKg", width: 18 },
    { header: "Remaining Bags", key: "remainingBags", width: 16 },
    { header: "Rate/Input Unit", key: "ratePerUnit", width: 14 },
    { header: "Grand Total", key: "grandTotal", width: 16 },
    { header: "Cost/KG", key: "costPerKg", width: 14 },
    { header: "Advance", key: "advanceAmount", width: 14 },
    { header: "Balance", key: "balanceAmount", width: 14 },
  ];

// Numeric columns (right-aligned, 2 decimal format)
const NUMERIC_KEYS = new Set<keyof PurchaseExportRow>([
  "quantityKg",
  "bags",
  "weightPerBagKg",
  "remainingQuantityKg",
  "remainingBags",
  "ratePerUnit",
  "grandTotal",
  "costPerKg",
  "advanceAmount",
  "balanceAmount",
]);

const HEADER_FILL: ExcelJS.Fill = {
  type: "pattern",
  pattern: "solid",
  fgColor: { argb: "FF1F3A5F" }, // deep navy
};

const HEADER_FONT: Partial<ExcelJS.Font> = {
  bold: true,
  color: { argb: "FFFFFFFF" },
  size: 11,
  name: "Calibri",
};

const TOTAL_FILL: ExcelJS.Fill = {
  type: "pattern",
  pattern: "solid",
  fgColor: { argb: "FFE8F4FD" }, // light blue tint
};

const ALT_FILL: ExcelJS.Fill = {
  type: "pattern",
  pattern: "solid",
  fgColor: { argb: "FFF6F8FA" }, // very light grey
};

const NUM_FORMAT = "#,##0.00";
const BORDER_STYLE: Partial<ExcelJS.Border> = { style: "thin", color: { argb: "FFD1D5DB" } };
const CELL_BORDER: Partial<ExcelJS.Borders> = {
  top: BORDER_STYLE,
  left: BORDER_STYLE,
  bottom: BORDER_STYLE,
  right: BORDER_STYLE,
};

/**
 * Generates a styled Purchase Excel report and streams it directly to the
 * Express Response object.
 *
 * @param rows    - Mapped purchase rows to include in the sheet.
 * @param res     - Express Response to pipe the workbook into.
 * @param filename - Optional filename (without .xlsx extension). Defaults to "purchase-report".
 */
export async function generatePurchaseExcel(
  rows: PurchaseExportRow[],
  res: Response,
  filename = "purchase-report"
): Promise<void> {
  const workbook = new ExcelJS.Workbook();
  workbook.creator = "AVS System";
  workbook.created = new Date();

  const sheet = workbook.addWorksheet("Purchase Report", {
    pageSetup: {
      paperSize: 9, // A4
      orientation: "landscape",
      fitToPage: true,
      fitToWidth: 1,
    },
    views: [{ state: "frozen", ySplit: 1 }],
  });

  // ── Columns ──────────────────────────────────────────────────────────────
  sheet.columns = COLUMNS.map((col) => ({
    header: col.header,
    key: col.key,
    width: col.width,
  }));

  // ── Style header row ─────────────────────────────────────────────────────
  const headerRow = sheet.getRow(1);
  headerRow.height = 28;
  headerRow.eachCell((cell) => {
    cell.fill = HEADER_FILL;
    cell.font = HEADER_FONT;
    cell.alignment = { vertical: "middle", horizontal: "center", wrapText: false };
    cell.border = CELL_BORDER;
  });

  // ── Data rows ─────────────────────────────────────────────────────────────
  rows.forEach((rowData, idx) => {
    const row = sheet.addRow(rowData);
    row.height = 20;

    const isAlt = idx % 2 !== 0;
    row.eachCell({ includeEmpty: true }, (cell, colNumber) => {
      const colKey = COLUMNS[colNumber - 1]?.key;

      // Alternating row bg
      if (isAlt) cell.fill = ALT_FILL;

      // Number formatting + right-align
      if (colKey && NUMERIC_KEYS.has(colKey)) {
        const raw = cell.value;
        const num = raw !== null && raw !== undefined && raw !== "" ? Number(raw) : null;
        cell.value = num;
        cell.numFmt = NUM_FORMAT;
        cell.alignment = { vertical: "middle", horizontal: "right" };
      } else {
        cell.alignment = { vertical: "middle", horizontal: "left" };
      }

      cell.font = { name: "Calibri", size: 10 };
      cell.border = CELL_BORDER;
    });
  });

  // ── Totals row ────────────────────────────────────────────────────────────
  if (rows.length > 0) {
    const dataStartRow = 2; // row index (1-indexed, header=1, data starts at 2)
    const dataEndRow = rows.length + 1;

    const totalRow = sheet.addRow({
      lotNo: "TOTAL",
      supplier: "",
      vegetable: "",
      quantityKg: { formula: `SUM(D${dataStartRow}:D${dataEndRow})` } as any,
      bags: { formula: `SUM(E${dataStartRow}:E${dataEndRow})` } as any,
      weightPerBagKg: { formula: `SUM(F${dataStartRow}:F${dataEndRow})` } as any,
      remainingQuantityKg: { formula: `SUM(G${dataStartRow}:G${dataEndRow})` } as any,
      remainingBags: { formula: `SUM(H${dataStartRow}:H${dataEndRow})` } as any,
      ratePerUnit: { formula: `SUM(I${dataStartRow}:I${dataEndRow})` } as any,
      grandTotal: { formula: `SUM(J${dataStartRow}:J${dataEndRow})` } as any,
      costPerKg: { formula: `SUM(K${dataStartRow}:K${dataEndRow})` } as any,
      advanceAmount: { formula: `SUM(L${dataStartRow}:L${dataEndRow})` } as any,
      balanceAmount: { formula: `SUM(M${dataStartRow}:M${dataEndRow})` } as any,
    });

    totalRow.height = 24;
    totalRow.eachCell({ includeEmpty: true }, (cell, colNumber) => {
      cell.fill = TOTAL_FILL;
      cell.font = { name: "Calibri", size: 10, bold: true };
      cell.border = CELL_BORDER;

      const colKey = COLUMNS[colNumber - 1]?.key;
      if (colKey && NUMERIC_KEYS.has(colKey)) {
        cell.numFmt = NUM_FORMAT;
        cell.alignment = { vertical: "middle", horizontal: "right" };
      } else {
        cell.alignment = { vertical: "middle", horizontal: "left" };
      }
    });
  }

  // ── Auto-filter on header ─────────────────────────────────────────────────
  sheet.autoFilter = {
    from: { row: 1, column: 1 },
    to: { row: 1, column: COLUMNS.length },
  };

  // ── Stream response ───────────────────────────────────────────────────────
  const safeFilename = encodeURIComponent(filename);
  res.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
  res.setHeader("Content-Disposition", `attachment; filename="${safeFilename}.xlsx"; filename*=UTF-8''${safeFilename}.xlsx`);
  res.setHeader("Access-Control-Expose-Headers", "Content-Disposition");

  await workbook.xlsx.write(res);
  res.end();
}

/**
 * Maps a raw Prisma purchase record to a flat PurchaseExportRow.
 */
export function mapPurchaseToExportRow(item: any): PurchaseExportRow {
  return {
    lotNo: item.lotNo ?? "",
    supplier: item.supplier?.name ?? item.cashSupplierName ?? item.supplierName ?? "",
    vegetable: item.vegetable?.name ?? "",
    quantityKg: Number(item.quantity ?? 0),
    bags: Number(item.bags ?? 0),
    weightPerBagKg: item.weightPerBag ? Number(item.weightPerBag) : "",
    remainingQuantityKg: Number(item.remainingQuantity ?? 0),
    remainingBags: Number(item.remainingBags ?? 0),
    ratePerUnit: Number(item.ratePerUnit ?? 0),
    grandTotal: Number(item.grandTotal ?? 0),
    costPerKg: Number(item.costPerUnit ?? 0),
    advanceAmount: Number(item.advanceAmount ?? 0),
    balanceAmount: Number(item.balanceAmount ?? 0),
  };
}
