"use client";

import { Download } from "lucide-react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";

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

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

function shouldOmitColumn(cell: Element, headerText: string): boolean {
  if (cell.hasAttribute("data-export-ignore")) {
    return true;
  }
  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,
      cell,
      text: cell.textContent ?? "",
    }))
    .filter((item) => shouldOmitColumn(item.cell, 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;
}

async function exportTableToWorkbook(table: HTMLTableElement, sheetName: string, filename: string): Promise<void> {
  const XLSX = await import("xlsx");
  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);
}

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

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

    try {
      await exportTableToWorkbook(table, sheetName, filename);
      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>
  );
}
