import React, { useContext } from "react";
import PropTypes from "prop-types";
import * as XLSX from "xlsx";
import { FiDownload } from "react-icons/fi";
import { langContext } from "../context/LenguageContext";

export default function ExcelExportButton({
  data,
  columns,
  filenamePrefix,
  sheetName,
  dataTransform = null,
  className = "",
  style = {},
}) {
  const { lang } = useContext(langContext);

  const handleExportToExcel = () => {
    if (!data || data.length === 0) {
      alert(lang === "es" ? "No hay datos para exportar" : "No data to export");
      return;
    }

    let dataToExport = dataTransform ? dataTransform(data) : data;

    const excelData = dataToExport.map((row) => {
      const excelRow = {};
      columns.forEach((column) => {
        if (column.key) {
          let value = row[column.key];

          // Handle render functions (extract text value)
          if (column.render && typeof column.render === "function") {
            // Try to get the raw value if render is used
            value = row[column.key];
          }

          if (value instanceof Date) {
            value = isNaN(value.getTime())
              ? ""
              : value.toLocaleDateString(lang === "es" ? "es-MX" : "en-US");
          }

          const header =
            typeof column.header === "string"
              ? column.header
              : (lang === "es" ? column.header?.es : column.header?.en) ||
                column.key;

          excelRow[header] = value || "";
        }
      });
      return excelRow;
    });

    const worksheet = XLSX.utils.json_to_sheet(excelData);
    const workbook = XLSX.utils.book_new();

    const finalSheetName =
      typeof sheetName === "string"
        ? sheetName
        : (lang === "es" ? sheetName?.es : sheetName?.en) || "Sheet1";

    XLSX.utils.book_append_sheet(workbook, worksheet, finalSheetName);

    const today = new Date();
    const dateStr = today.toISOString().split("T")[0];
    const filename = `${filenamePrefix}-${dateStr}.xlsx`;

    XLSX.writeFile(workbook, filename);
  };

  const defaultStyle = {
    backgroundColor: "#ffcb05",
    color: "#fff",
    padding: "10px 20px",
    fontWeight: "bold",
    border: "none",
    borderRadius: "8px",
    cursor: "pointer",
    display: "flex",
    alignItems: "center",
    gap: "8px",
    fontSize: "14px",
    transition: "background-color 0.3s ease",
    ...style,
  };

  return (
    <button
      onClick={handleExportToExcel}
      className={className}
      style={defaultStyle}
      onMouseEnter={(e) => (e.target.style.backgroundColor = "#f4b400")}
      onMouseLeave={(e) => (e.target.style.backgroundColor = "#ffcb05")}
    >
      <FiDownload />
      {lang === "es" ? "Exportar a Excel" : "Export to Excel"}
    </button>
  );
}

ExcelExportButton.propTypes = {
  data: PropTypes.arrayOf(PropTypes.object).isRequired,
  columns: PropTypes.arrayOf(
    PropTypes.shape({
      header: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
      key: PropTypes.string.isRequired,
      render: PropTypes.func,
    })
  ).isRequired,
  filenamePrefix: PropTypes.string.isRequired,
  sheetName: PropTypes.oneOfType([PropTypes.string, PropTypes.object])
    .isRequired,
  dataTransform: PropTypes.func,
  className: PropTypes.string,
  style: PropTypes.object,
};
