"use client";

import { Download } from "lucide-react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import * as XLSX from "xlsx";

import { Button } from "@/components/ui/button";

const OMIT_HEADER_TOKENS = [
  "actions",
  "action",
  "操作",
  "下载",
  "download",
] as const;

function shouldOmitColumn(headerText: string): boolean {
  const normalized = headerText.trim().toLowerCase();
  if (normalized === "") {
    return true;
  }
  return OMIT_HEADER_TOKENS.some((token) => normalized.includes(token));
}

function stripOmittedColumns(table: HTMLTableElement): HTMLTableElement {
  const clone = table.cloneNode(true) as HTMLTableElement;
  const headerRow = clone.querySelector("thead tr");
  if (!headerRow) {
    return clone;
  }

  const omitIndexes = Array.from(headerRow.children)
    .map((cell, index) => ({
      index,
      text: cell.textContent ?? "",
    }))
    .filter((item) => shouldOmitColumn(item.text))
    .map((item) => item.index)
    .sort((a, b) => b - a);

  if (omitIndexes.length === 0) {
    return clone;
  }

  clone.querySelectorAll("tr").forEach((row) => {
    const cells = Array.from(row.children);
    omitIndexes.forEach((index) => {
      const target = cells[index];
      if (target) {
        target.remove();
      }
    });
  });

  return clone;
}

export function AdminTableExportButton({
  tableId,
  filename,
  sheetName = "Sheet1",
  label,
}: {
  tableId: string;
  filename: string;
  sheetName?: string;
  label?: string;
}) {
  const { t } = useTranslation("common");

  const onExport = () => {
    const table = document.getElementById(tableId);
    if (!(table instanceof HTMLTableElement)) {
      toast.error(t("toast.exportFailed"));
      return;
    }

    try {
      const exportTable = stripOmittedColumns(table);
      const workbook = XLSX.utils.table_to_book(exportTable, {
        sheet: sheetName,
        raw: true,
      });
      const safeName = filename.endsWith(".xlsx") ? filename : `${filename}.xlsx`;
      XLSX.writeFile(workbook, safeName);
      toast.success(t("toast.exportDone"));
    } catch {
      toast.error(t("toast.exportFailed"));
    }
  };

  return (
    <Button type="button" size="sm" variant="secondary" onClick={onExport}>
      <Download className="size-4" />
      {label ?? t("actions.exportExcel")}
    </Button>
  );
}
