"use client";
import React, { useState } from "react";
import { Table, Button } from "react-bootstrap";
import styles from "@/styles/Component/Dashboard/MonthlySummaryReport.module.scss";
import useFetchData from "@/components/App/useFetchData";
import { SuspenseLoader } from "@/components/App/Loader";
import TableNoData from "@/components/common/TableNoData";
import { formatDateWithFormatType, toastrC } from "@/utils/helpers";
import { useRequest } from "@/components/App/request";

/*!SECTION{
    "date": "2025-03",
    "debit": 3,
    "credit": 0,
    "total": -3
}
    */
interface MonthlyStatementResponse {
  date: string;
  debit: number;
  credit: number;
  total: number;
}

const MonthlySummaryReport = () => {
  const { data, isLoading } = useFetchData<MonthlyStatementResponse[]>(
    "MONTHLY_LEAD_REPORT",
    []
  );
  const [isDownloading, setIsDownloading] = useState(false);
  const { request } = useRequest();
  const handleDownload = async () => {
    setIsDownloading(true);
    try {
      const res = await request(
        "DOWNLOAD_MONTHLY_STATEMENT_REPORT",
        {},
        {},
        { responseType: "blob" }
      );
      // Ensure response is a valid Blob
      if (!res || !(res instanceof Blob)) {
        toastrC("Invalid response, expected a Blob", "error", "error");
        return;
      }
      // Create a download link
      const url = window.URL.createObjectURL(res);
      const a = document.createElement("a");
      a.href = url;
      a.download = `monthly-summary-report.xlsx`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
    } catch (e) {
      console.log(e);
    } finally {
      setIsDownloading(false); // Reset loading state
    }
  };

  if (isLoading) return <SuspenseLoader />;

  return (
    <div className={styles.MonthlySummaryReportBlock}>
      <div className="row">
        <h1 className="col-md-6">Monthly Summary Report</h1>
        <div className="col-md-6 d-flex  justify-content-end mb-3">
          <Button
            className={styles.BtnCustom}
            type="button"
            onClick={() => handleDownload()}
            disabled={isDownloading}
          >
            {isDownloading ? "Downloading..." : "Download"}
          </Button>
        </div>
      </div>
      <div className="customTableCard text-center">
        <Table responsive>
          <thead>
            <tr>
              <th>Date</th>
              <th>Description</th>
              <th>Debit</th>
              <th>Credit</th>
              <th>Balance</th>
            </tr>
          </thead>
          <tbody>
            {Array.isArray(data) ? (
              data.map((item, index) => (
                <tr key={index}>
                  <td>{formatDateWithFormatType(item.date, "MMM-YY")}</td>
                  <td>{item.credit > 0 ? "Credit" : "Debit"}</td>
                  <td>{item.debit || "-"}</td>
                  <td>{item.credit || "-"}</td>
                  <td>{item.total || "-"}</td>
                </tr>
              ))
            ) : (
              <TableNoData isLoading={isLoading} colSpan={5} />
            )}
          </tbody>
        </Table>
      </div>
    </div>
  );
};

export default MonthlySummaryReport;
