import ExcelJS from "exceljs";

export type AttendanceReportType =
  | "DAILY"
  | "EMPLOYEE"
  | "MONTHLY_SUMMARY"
  | "REGISTER"
  | "ABSENT"
  | "HALF_DAY"
  | "ATTENDANCE_SUMMARY";

export interface AttendanceExportDataPayload {
  reportType: AttendanceReportType;
  title: string;
  subtitle?: string | undefined;
  records: any[];
  summary?: any;
  daysInMonth?: number | undefined;
}

export const generateUnifiedAttendanceExcel = async (payload: AttendanceExportDataPayload): Promise<ExcelJS.Workbook> => {
  const workbook = new ExcelJS.Workbook();
  const sheet = workbook.addWorksheet("Attendance Report");

  const primaryColor = "FF0F5132"; // Emerald green
  const headerFontColor = "FFFFFFFF"; // White

  // 1. Title Row
  sheet.mergeCells("A1", "G1");
  const titleCell = sheet.getCell("A1");
  titleCell.value = payload.title.toUpperCase();
  titleCell.font = { bold: true, size: 14, color: { argb: primaryColor } };
  titleCell.alignment = { horizontal: "center", vertical: "middle" };
  sheet.getRow(1).height = 30;

  // 2. Subtitle Row
  let currentRowIndex = 3;
  if (payload.subtitle) {
    sheet.mergeCells("A2", "G2");
    const subCell = sheet.getCell("A2");
    subCell.value = payload.subtitle;
    subCell.font = { italic: true, size: 10, color: { argb: "FF555555" } };
    subCell.alignment = { horizontal: "center", vertical: "middle" };
    currentRowIndex = 4;
  }

  // 3. Render Table Headers & Rows based on Report Type
  if (payload.reportType === "REGISTER") {
    const days = payload.daysInMonth || 31;
    const columns: Partial<ExcelJS.Column>[] = [
      { header: "S.No", key: "sNo", width: 6 },
      { header: "Employee Code", key: "employeeCode", width: 14 },
      { header: "Employee Name", key: "employeeName", width: 22 },
    ];

    for (let d = 1; d <= days; d++) {
      columns.push({ header: `${d}`, key: `d_${d}`, width: 5 });
    }

    const headerRow = sheet.getRow(currentRowIndex);
    headerRow.values = columns.map((c) => c.header as string);
    headerRow.font = { bold: true, color: { argb: headerFontColor } };
    headerRow.fill = { type: "pattern", pattern: "solid", fgColor: { argb: primaryColor } };
    headerRow.alignment = { horizontal: "center", vertical: "middle" };

    payload.records.forEach((rec, idx) => {
      currentRowIndex++;
      const rowValues: any[] = [idx + 1, rec.employeeCode, rec.name];
      for (let d = 1; d <= days; d++) {
        const st = rec.daily?.[d]?.status;
        rowValues.push(st === "PRESENT" ? "P" : st === "ABSENT" ? "A" : st === "HALF_DAY" ? "HD" : "-");
      }
      sheet.getRow(currentRowIndex).values = rowValues;
    });

  } else if (payload.reportType === "MONTHLY_SUMMARY" || payload.reportType === "ATTENDANCE_SUMMARY") {
    const headers = [
      { header: "S.No", key: "sNo", width: 8 },
      { header: "Employee Code", key: "employeeCode", width: 16 },
      { header: "Employee Name", key: "employeeName", width: 25 },
      { header: "Total Days", key: "totalDays", width: 12 },
      { header: "Present", key: "present", width: 12 },
      { header: "Absent", key: "absent", width: 12 },
      { header: "Half Day", key: "halfDay", width: 12 },
      { header: "Attendance %", key: "attendanceRate", width: 15 },
    ];

    const headerRow = sheet.getRow(currentRowIndex);
    headerRow.values = headers.map((h) => h.header);
    headerRow.font = { bold: true, color: { argb: headerFontColor } };
    headerRow.fill = { type: "pattern", pattern: "solid", fgColor: { argb: primaryColor } };
    headerRow.alignment = { horizontal: "center", vertical: "middle" };

    payload.records.forEach((rec, idx) => {
      currentRowIndex++;
      const stats = rec.stats || {};
      sheet.getRow(currentRowIndex).values = [
        idx + 1,
        rec.employeeCode,
        rec.name || rec.employeeName,
        stats.totalDays || payload.daysInMonth || 30,
        stats.presentDays ?? 0,
        stats.absentDays ?? 0,
        stats.halfDays ?? 0,
        `${stats.attendanceRate ?? stats.attendancePercentage ?? 0}%`,
      ];
    });

  } else if (payload.reportType === "EMPLOYEE") {
    const headers = [
      { header: "S.No", key: "sNo", width: 8 },
      { header: "Date", key: "date", width: 15 },
      { header: "Status", key: "status", width: 15 },
      { header: "Remarks", key: "remarks", width: 30 },
    ];

    const headerRow = sheet.getRow(currentRowIndex);
    headerRow.values = headers.map((h) => h.header);
    headerRow.font = { bold: true, color: { argb: headerFontColor } };
    headerRow.fill = { type: "pattern", pattern: "solid", fgColor: { argb: primaryColor } };

    payload.records.forEach((rec, idx) => {
      currentRowIndex++;
      sheet.getRow(currentRowIndex).values = [idx + 1, rec.date, rec.status, rec.remarks || "-"];
    });

    if (payload.summary) {
      currentRowIndex += 2;
      const sumRow = sheet.getRow(currentRowIndex);
      sumRow.values = [
        "SUMMARY STATS",
        `Total Days: ${payload.summary.totalDays}`,
        `Present: ${payload.summary.presentDays}`,
        `Absent: ${payload.summary.absentDays}`,
        `Half Day: ${payload.summary.halfDays}`,
        `Rate: ${payload.summary.attendancePercentage}%`,
      ];
      sumRow.font = { bold: true };
    }

  } else {
    // DAILY, ABSENT, HALF_DAY
    const headers = [
      { header: "S.No", key: "sNo", width: 8 },
      { header: "Date", key: "date", width: 15 },
      { header: "Employee Code", key: "employeeCode", width: 16 },
      { header: "Employee Name", key: "employeeName", width: 25 },
      { header: "Status", key: "status", width: 15 },
      { header: "Remarks", key: "remarks", width: 30 },
    ];

    const headerRow = sheet.getRow(currentRowIndex);
    headerRow.values = headers.map((h) => h.header);
    headerRow.font = { bold: true, color: { argb: headerFontColor } };
    headerRow.fill = { type: "pattern", pattern: "solid", fgColor: { argb: primaryColor } };

    payload.records.forEach((rec, idx) => {
      currentRowIndex++;
      sheet.getRow(currentRowIndex).values = [
        idx + 1,
        rec.date || "-",
        rec.employeeCode || "-",
        rec.employeeName || rec.name || "-",
        rec.status || "-",
        rec.remarks || "-",
      ];
    });
  }

  // Border formatting for all cells
  sheet.eachRow((row) => {
    row.eachCell((cell) => {
      cell.border = {
        top: { style: "thin", color: { argb: "FFE0E0E0" } },
        left: { style: "thin", color: { argb: "FFE0E0E0" } },
        bottom: { style: "thin", color: { argb: "FFE0E0E0" } },
        right: { style: "thin", color: { argb: "FFE0E0E0" } },
      };
    });
  });

  return workbook;
};
