"use client";

import { useState } from "react";
import { saveAs } from "file-saver";
import ExcelJS from "exceljs";

import styles from "./style.module.css";

interface Recibo {
  id_recibo: number;
  folio_recibo: string;
  fecha_recibo: string;
  fecha_registro: string;
  monto: string;
  user: {
    usuario: string;
  };
}

interface Columns{
  header:string;
  key:string;
  width:number
}

interface Props {
  data: Recibo[];
  columns:Columns[];
}

export default function DownloadReporteXLSX({ data,columns }: Props) {
  const [loading, setLoading] = useState(false);

  const formatearFechaMX = (fechaISO: string) => {
    return new Date(fechaISO).toLocaleString("es-MX", {
      timeZone: "America/Mexico_City",
    });
  };

  const handleDownload = async () => {
    if (!data || data.length === 0) return;

    setLoading(true);

    try {
      const workbook = new ExcelJS.Workbook();
      const worksheet = workbook.addWorksheet("Recibos");

      worksheet.columns = columns;

      data.forEach((recibo) => {
        worksheet.addRow({
          folio: recibo.folio_recibo,
          monto: Number(recibo.monto),
          fechaRecibo: recibo.fecha_recibo,
          fechaRegistro: formatearFechaMX(recibo.fecha_registro),
          usuario: recibo.user.usuario,
        });
      });

      worksheet.getColumn("monto").numFmt = '"$"#,##0.00';

      const buffer = await workbook.xlsx.writeBuffer();
      const blob = new Blob([buffer], {
        type:
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      });

      saveAs(blob, "Reporte_Recibos.xlsx");
    } catch (error) {
      console.error("Error generando Excel", error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <button
      className={styles.downloadBtn}
      onClick={handleDownload}
      disabled={loading}
    >
      {loading ? (
        <div className={styles.loader}></div>
      ) : (
        <img
          src="/excel.svg"
          alt="Excel"
          className={styles.iconExcel}
          width={30}
          height={30}
        />
      )}
    </button>
  );
}
