import moment from "moment";
import {
  exportToCSV,
  exportToExcel,
  exportToPDF,
  printTable,
} from "../../utils/tableExportUtils";
import { FREQUENCY_FOR_RECURRING } from "../../utils/constants";
import ExpenseRepository from "../../repositories/ExpsenseRepository";

const HandleRecurringExpenseExport = async (
  type,
  filters = {},
  searchString = "",
  tableRef = null,
  setLoading = null
) => {
  try {
    if (setLoading) setLoading(true);

    const safeSearchString =
      typeof searchString === "string" ? searchString : "";
    let allRecurringExpense = [];
    let pageNumber = 1;
    const pageSize = 1000;
    let hasMore = true;

    while (hasMore) {
      const response = await ExpenseRepository.GetRecurringExpenseList(
        pageSize,
        pageNumber,
        filters,
        true, // isActive
        safeSearchString
      );

      const currentPageData = response?.data?.data || [];
      allRecurringExpense = allRecurringExpense.concat(currentPageData);

      if (currentPageData.length < pageSize) {
        hasMore = false;
      } else {
        pageNumber += 1;
      }
    }

    if (!allRecurringExpense.length) {
      console.warn("No payment requests found!");
      return;
    }

    const exportData = allRecurringExpense.map((item) => ({
      Category: item?.expenseCategory?.name ?? "-",
      Title: item?.title ?? "-",
      Payee: item?.payee ?? "-",
      Frequency:
        item?.frequency !== undefined && item?.frequency !== null
          ? FREQUENCY_FOR_RECURRING[item?.frequency] ?? "-"
          : "-",
      Amount: item?.amount ? item.amount.toLocaleString() : "-",
      Currency: item?.currency?.symbol ?? "-",
      "Next Generation Date": item?.nextGenerationDate
        ? moment(item.nextGenerationDate).format("DD-MMM-YYYY")
        : "-",
      Status: item?.status?.name ?? "-",
      "Created At": item?.createdAt
        ? moment(item.createdAt).format("DD-MMM-YYYY")
        : "-",
    }));

    // COLUMN ORDER
    const columns = [
      "Category",
      "Title",
      "Payee",
      "Frequency",
      "Amount",
      "Currency",
      "Next Generation Date",
      "Status",
      "Created At",
    ];

    switch (type) {
      case "csv":
        exportToCSV(exportData, "recurring-expense", columns);
        break;
      case "excel":
        exportToExcel(exportData, "recurring-expense", columns);
        break;
      case "pdf":
        exportToPDF(exportData, "recurring-expense", columns);
        break;
      case "print":
        if (tableRef?.current) printTable(tableRef.current);
        break;
      default:
        console.warn("Unknown export type:", type);
    }
  } catch (err) {
    console.error("Export failed:", err);
  } finally {
    if (setLoading) setLoading(false);
  }
};

export default HandleRecurringExpenseExport;
