/**
 * Botón para exportar documentos a Excel
 */

"use client";

import { FC } from "react";
import { Table } from "@tanstack/react-table";
import { Documento } from "@/types/document";
import { LuDownload } from "react-icons/lu";
import * as XLSX from "xlsx";
import { findInExtractedData } from "./utils";

interface ExportButtonProps {
  table: Table<Documento>;
  empleados: { id: string; nombre: string }[];
  filtroUsuario?: string;
}

const ExportButton: FC<ExportButtonProps> = ({
  table,
  empleados,
  filtroUsuario,
}) => {
  const handleExport = () => {
    // Obtener las filas filtradas
    const filteredRows = table.getFilteredRowModel().rows;

    // Headers fijos según especificación
    const headers = [
      "NOMBRE",
      "CODIGO",
      "RNC",
      "NCF",
      "CATEGORIAS",
      "TIPO DE GASTO",
      "FORMA DE PAGO",
      "SUB-TOTAL",
      "ITBIS",
      "PROPINA",
      "TOTAL",
      "FECHA",
    ];

    // Preparar datos con los campos especificados
    const rows = filteredRows.map((row) => {
      const doc = row.original;
      const extracted = doc.extractedData as Record<string, unknown> | undefined;

      return [
        // Nombre del empleado
        doc.owner?.name || doc.owner?.username || "",
        // Código (username del empleado)
        doc.owner?.username || "",
        // RNC del documento
        findInExtractedData(extracted, ["rnc", "rncCedula", "rnc_cedula"]),
        // NCF del documento
        findInExtractedData(extracted, ["ncf", "nfc", "ncfFactura", "ncf_factura"]),
        // Categoría
        doc.category?.name || "",
        // Tipo de Gasto
        doc.category?.expenseType || "",
        // Forma de Pago
        doc.category?.paymentMethod || "",
        // Sub-total
        findInExtractedData(extracted, ["subtotal", "sub_total", "subTotal"]),
        // ITBIS
        findInExtractedData(extracted, ["itbis", "iva", "impuesto"]),
        // Propina
        findInExtractedData(extracted, ["propina", "tip", "servicio"]),
        // Total
        findInExtractedData(extracted, ["total", "totalGeneral", "total_general", "montoTotal"]),
        // Fecha del documento
        findInExtractedData(extracted, ["fecha", "date", "fechaFactura", "fecha_factura"]) ||
        new Date(doc.createdAt).toLocaleDateString('es-ES'),
      ];
    });

    // Crear workbook y worksheet
    const worksheet = XLSX.utils.aoa_to_sheet([headers, ...rows]);

    // Ajustar ancho de columnas automáticamente
    const maxWidth = 50;
    const columnWidths = headers.map((header, i) => {
      const maxLength = Math.max(
        header.length,
        ...rows.map(row => String(row[i] || "").length)
      );
      return { wch: Math.min(maxLength + 2, maxWidth) };
    });
    worksheet['!cols'] = columnWidths;

    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, "Documentos");

    // Nombre del archivo incluye el filtro si existe
    const fileName = filtroUsuario
      ? `documentos_${empleados.find((e) => e.id === filtroUsuario)?.nombre || "filtrados"
      }.xlsx`
      : "documentos.xlsx";

    // Generar y descargar archivo Excel
    XLSX.writeFile(workbook, fileName);
  };

  return (
    <button
      onClick={handleExport}
      className="flex items-center gap-2 px-4 py-2.5 border border-gray-200 rounded-lg bg-white text-sm font-medium text-gray-700 hover:bg-gray-50 focus:ring-2 focus:ring-blue-500 outline-none transition-colors shadow-sm"
    >
      <LuDownload className="h-4 w-4 text-gray-500" />
      <span>Exportar Excel</span>
    </button>
  );
};

export default ExportButton;
