import ExpenseRepository from "../../repositories/ExpsenseRepository";
import moment from "moment";
import { exportToCSV, exportToExcel, exportToPDF, printTable } from "../../utils/tableExportUtils";
import showToast from "../../services/toastService";

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

    const safeSearchString = typeof searchString === "string" ? searchString : "";
    let allExpenses = [];
    let pageNumber = 1;
    const pageSize = 1000; // fetch 1000 per API call
    let hasMore = true;

    while (hasMore) {
      const response = await ExpenseRepository.GetExpenseList(
        pageSize,
        pageNumber,
        filters,
        safeSearchString
      );

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

      // If returned data length is less than pageSize, we reached the last page
      if (currentPageData.length < pageSize) {
        hasMore = false;
      } else {
        pageNumber += 1; // fetch next page
      }
    }

    if (!allExpenses.length) {
      showToast("No expenses found!", "warning");
      return;
    }

    // Map export data
    const exportData = allExpenses.map((item) => ({
      "Expense ID": item?.expenseUId ?? "-",
      "Expense Category": item?.expenseCategory?.name ?? "-",
      "Payment Mode": item?.paymentMode?.name ?? "-",
      "Submitted By": `${item?.createdBy?.firstName ?? ""} ${item?.createdBy?.lastName ?? ""}`.trim() || "-",
      "Submitted": item?.createdAt ? moment(item.createdAt).format("DD-MMM-YYYY") : "-",
      "Amount": item?.amount != null
        ? `${item.amount.toLocaleString()} ${item.currency?.currencyCode ?? ""}`
        : "-",
      "Status": item?.status?.name ?? "-",
    }));


    switch (type) {
      case "csv":
        exportToCSV(exportData, "Expenses");
        break;
      case "excel":
        exportToExcel(exportData, "Expenses");
        break;
      case "pdf":
        exportToPDF(exportData, "Expenses");
        break;
      case "print":
        if (tableRef?.current) printTable(tableRef.current);
        break;
      default:
        console.warn("Unknown export type:", type);
    }

  } catch (err) {
    console.error(err);
    showToast("Failed to export expenses", "error");
  } finally {
    if (setLoading) setLoading(false);
  }
};

export default HandleExpenseExport;
