"use client";

import styles from "./style.module.css";
import Cookies from "js-cookie";
import { useState } from "react";
import axios from "axios";

interface Props {
  filtros: any;
  count?: boolean;
}

export default function DownloadTable({ filtros,count }: Props) {
  const [loading, setLoading] = useState(false);

  const handleDownload = async () => {
    if(!filtros.length){return}
    setLoading(true);

    const token = Cookies.get("token");

    try {
      const endpoint = count
  ? "/equipos/excel/tabla/count"
  : "/equipos/excel/tabla";


      const response = await axios.post(
        `${process.env.NEXT_PUBLIC_API_URL}${endpoint}`,
        filtros,
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
          responseType: "blob",
        }
      );
      const url = window.URL.createObjectURL(new Blob([response.data]));

      const a = document.createElement("a");
      a.href = url;
      a.download = "reporte.xlsx";
      document.body.appendChild(a);
      a.click();
      a.remove();

      window.URL.revokeObjectURL(url);
    } catch (error) {
      console.error(error);
      alert("Hubo un problema al descargar el archivo.");
    } 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>
  );
}