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

export interface VegWiseSaleExportRow {
  invoiceNo: string;
  invoiceDate: string;
  customerName: string;
  vegetableName: string;
  quantity: number | string;
  soldBy: string;
  bags: number | string;
  rate: number | string;
  amount: number | string;
}

const COLUMNS: { header: string; key: keyof VegWiseSaleExportRow; width: number }[] = [
  { header: "Invoice No", key: "invoiceNo", width: 18 },
  { header: "Sold Date", key: "invoiceDate", width: 16 },
  { header: "Customer Name", key: "customerName", width: 24 },
  { header: "Vegetable Name", key: "vegetableName", width: 20 },
  { header: "Quantity (KG)", key: "quantity", width: 16 },
  { header: "Sold By", key: "soldBy", width: 12 },
  { header: "Bags", key: "bags", width: 12 },
  { header: "Rate (INR/KG)", key: "rate", width: 16 },
  { header: "Amount", key: "amount", width: 16 },
];

const NUMERIC_KEYS = new Set<keyof VegWiseSaleExportRow>([
  "quantity",
  "bags",
  "rate",
  "amount",
]);

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

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

export async function generateVegWiseSaleExcel(
  rows: VegWiseSaleExportRow[],
  res: Response,
  filename = "vegetable-wise-sales-report"
): Promise<void> {
  const workbook = new ExcelJS.Workbook();
  workbook.creator = "AVS System";
  workbook.created = new Date();

  const sheet = workbook.addWorksheet("Vegetable-wise Sales", {
    pageSetup: {
      paperSize: 9, // A4
      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({
      invoiceNo: "TOTAL",
      invoiceDate: "",
      customerName: "",
      vegetableName: "",
      quantity: { formula: `SUM(E${dataStartRow}:E${dataEndRow})` } as any,
      soldBy: "",
      bags: { formula: `SUM(G${dataStartRow}:G${dataEndRow})` } as any,
      rate: { formula: `SUM(H${dataStartRow}:H${dataEndRow})` } as any,
      amount: { formula: `SUM(I${dataStartRow}:I${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" };
      }
    });
  }

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

export function mapVegWiseSaleToExportRow(item: any): VegWiseSaleExportRow {
  let invoiceDateStr = "";
  if (item.sale?.invoiceDate) {
    invoiceDateStr = new Date(item.sale.invoiceDate as string).toISOString().slice(0, 10);
  }
  return {
    invoiceNo: item.sale?.invoiceNo ?? "",
    invoiceDate: invoiceDateStr,
    customerName: item.sale?.customer?.name || item.sale?.walkInName || "",
    vegetableName: item.purchase?.vegetable?.name ?? "",
    quantity: Number(item.quantity ?? 0),
    soldBy: item.saleUnit ?? "KG",
    bags: Number(item.bags ?? 0),
    rate: Number(item.quantity ?? 0) > 0 ? Number(item.total ?? 0) / Number(item.quantity ?? 0) : 0,
    amount: Number(item.total ?? 0),
  };
}

