import { Button, Tooltip } from "@mantine/core";
import { IconFileSpreadsheet } from "@tabler/icons-react";
import { ExportButton } from "@/lib/export/ExportButton";
import type { ExportData } from "@/lib/export/ExportButton";

type Props<T extends Record<string, unknown>> = {
  label: string;
  filename: string;
  filtersSummary?: string;
  getData: (signal: AbortSignal) => Promise<ExportData<T>>;
  /** `event-analytics:update` from the route loader. */
  canExport: boolean;
};

/**
 * Export action for the Event Analytics pages.
 *
 * `ExportButton` renders nothing at all when the user lacks the privilege,
 * which is right for a page where the absence is obvious but wrong here: the
 * export was simply missing with no explanation, and "export is not working"
 * is indistinguishable from "you are not allowed to export". A disabled control
 * that names the missing privilege costs one line and answers the question.
 */
export default function EventExportButton<T extends Record<string, unknown>>({
  label,
  filename,
  filtersSummary,
  getData,
  canExport,
}: Props<T>) {
  if (!canExport) {
    return (
      <Tooltip
        label="You need the Event Analytics “update” privilege to export. Ask an admin to grant it in Role Management."
        multiline
        w={280}
        withArrow
      >
        <Button
          variant="light"
          color="gray"
          leftSection={<IconFileSpreadsheet size={16} />}
          data-disabled
          // Not the `disabled` prop: a disabled button swallows pointer events,
          // and the tooltip explaining *why* is the whole point of showing it.
          onClick={(event) => event.preventDefault()}
          styles={{ root: { cursor: "not-allowed" } }}
        >
          {label}
        </Button>
      </Tooltip>
    );
  }

  return (
    <ExportButton
      label={label}
      filename={filename}
      section="reports"
      roleSlug="event-analytics"
      filtersSummary={filtersSummary}
      getData={getData}
    />
  );
}
