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

export interface ArrivalSettlementExportRow {
  settlementNo: string;
  settlementDate: string;
  lotNo: string;
  supplier: string;
  vegetable: string;
  weightSoldKg: number | string;
  grossSales: number | string;
  commissionPct: number | string;
  commissionAmt: number | string;
  totalDeductions: number | string;
  netPayable: number | string;
  paidAmount: number | string;
  balanceAmount: number | string;
  status: string;
}

const COLUMNS: { header: string; key: keyof ArrivalSettlementExportRow; width: number }[] = [
  { header: "Patti No",            key: "settlementNo",    width: 22 },
  { header: "Settlement Date",     key: "settlementDate",  width: 16 },
  { header: "Lot No",              key: "lotNo",           width: 16 },
  { header: "Supplier / Farmer",   key: "supplier",        width: 26 },
  { header: "Vegetable",           key: "vegetable",       width: 20 },
  { header: "Weight Sold (KG)",    key: "weightSoldKg",    width: 16 },
  { header: "Gross Sales (Rs)",    key: "grossSales",      width: 16 },
  { header: "Commission %",        key: "commissionPct",   width: 14 },
  { header: "Commission (Rs)",     key: "commissionAmt",   width: 16 },
  { header: "Total Deductions",    key: "totalDeductions", width: 16 },
  { header: "Net Payable (Rs)",    key: "netPayable",      width: 16 },
  { header: "Paid Amount (Rs)",    key: "paidAmount",      width: 16 },
  { header: "Balance (Rs)",        key: "balanceAmount",   width: 16 },
  { header: "Status",              key: "status",          width: 20 },
];

const NUMERIC_KEYS = new Set<keyof ArrivalSettlementExportRow>([
  "weightSoldKg",
  "grossSales",
  "commissionPct",
  "commissionAmt",
  "totalDeductions",
  "netPayable",
  "paidAmount",
  "balanceAmount",
]);

const HEADER_FILL: ExcelJS.Fill = {
  type: "pattern",
  pattern: "solid",
  fgColor: { argb: "FF0F5132" },
};

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: "FFD1E7DD" },
};

const ALT_FILL: ExcelJS.Fill = {
  type: "pattern",
  pattern: "solid",
  fgColor: { argb: "FFF8F9FA" },
};

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 Arrival Settlements Excel report and streams it to the Response.
 */
export async function generateArrivalSettlementExcel(
  rows: ArrivalSettlementExportRow[],
  res: Response,
  filename = "arrival-settlements-report"
): Promise<void> {
  const workbook = new ExcelJS.Workbook();
  workbook.creator = "AVS System";
  workbook.created = new Date();

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

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

  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;
  });

  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;

      if (isAlt) cell.fill = ALT_FILL;

      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;
    });
  });

  if (rows.length > 0) {
    const dataStartRow = 2;
    const dataEndRow = rows.length + 1;

    const totalRow = sheet.addRow({
      settlementNo:    "TOTAL",
      settlementDate:  "",
      lotNo:           "",
      supplier:        "",
      vegetable:       "",
      weightSoldKg:    { formula: `SUM(F${dataStartRow}:F${dataEndRow})` } as any,
      grossSales:      { formula: `SUM(G${dataStartRow}:G${dataEndRow})` } as any,
      commissionPct:   "",
      commissionAmt:   { formula: `SUM(I${dataStartRow}:I${dataEndRow})` } as any,
      totalDeductions: { formula: `SUM(J${dataStartRow}:J${dataEndRow})` } as any,
      netPayable:      { formula: `SUM(K${dataStartRow}:K${dataEndRow})` } as any,
      paidAmount:      { formula: `SUM(L${dataStartRow}:L${dataEndRow})` } as any,
      balanceAmount:   { formula: `SUM(M${dataStartRow}:M${dataEndRow})` } as any,
      status:          "",
    });

    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" };
      }
    });
  }

  sheet.autoFilter = {
    from: { row: 1, column: 1 },
    to: { row: 1, column: COLUMNS.length },
  };

  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 ArrivalSettlement record to a flat ArrivalSettlementExportRow.
 */
export function mapArrivalSettlementToExportRow(item: any): ArrivalSettlementExportRow {
  const arrival = item.purchase || {};
  return {
    settlementNo:    item.settlementNo ?? "",
    settlementDate:  item.settlementDate
      ? new Date(item.settlementDate).toLocaleDateString("en-GB").replace(/\//g, "-")
      : "",
    lotNo:           arrival.lotNo ?? "",
    supplier:        arrival.supplier?.name ?? arrival.cashSupplierName ?? arrival.agentName ?? "",
    vegetable:       arrival.vegetable?.name ?? "",
    weightSoldKg:    Number(item.totalWeightSold ?? 0),
    grossSales:      Number(item.grossSalesTotal ?? 0),
    commissionPct:   Number(item.commissionPercent ?? 0),
    commissionAmt:   Number(item.commissionAmount ?? 0),
    totalDeductions: Number(item.totalDeductions ?? 0),
    netPayable:      Number(item.netPayable ?? 0),
    paidAmount:      Number(item.paidAmount ?? 0),
    balanceAmount:   Number(item.balanceAmount ?? 0),
    status:          item.status ?? "",
  };
}
