import { Button } from "@mantine/core";
import type { TFunction } from "i18next";
import type { LicenseApplication } from "@ema-platform/api";
import type { AdvancedColumn } from "@ema-platform/ui";
import { LICENSE_PERMISSIONS, RequirePermission } from "@ema-platform/auth";

export function licenseQueueActionsColumn(
  t: TFunction,
  handlers: {
    assigning: boolean;
    /** Opens the assign dialog. Team leaders only — see below. */
    onAssign: (application: LicenseApplication) => void;
    onOpen: (id: string) => void;
    /** False for a non-logistics queue — nothing there is dispatched. */
    assignable?: boolean;
  },
): AdvancedColumn<LicenseApplication> {
  return {
    header: "",
    label: t("queue.actionsColumn", "Actions"),
    align: "right",
    size: 140,
    /**
     * "Assign", not "Claim".
     *
     * Work is pushed, not picked up: an unassigned application is waiting for
     * the team leader to hand it to someone, and no seeded position type holds
     * `CLAIM_APPLICATION` any more. Guarded on `ASSIGN_APPLICATION`, so an
     * employee sees only "Review" on the files that are already theirs.
     */
    cell: ({ row }) =>
      handlers.assignable !== false &&
      row.original.assignedOfficerId === null &&
      // Mirrors the ASSIGN_REVIEWER transition's `from` list: an examined cert
      // (CoC/CoP) sits in ELIGIBILITY_PAID once its eligibility fee clears,
      // not SUBMITTED.
      (row.original.status === "SUBMITTED" ||
        row.original.status === "ELIGIBILITY_PAID") ? (
        <RequirePermission
          anyOf={[LICENSE_PERMISSIONS.ASSIGN_APPLICATION]}
          hideOnly
        >
          <Button
            size="xs"
            loading={handlers.assigning}
            onClick={() => handlers.onAssign(row.original)}
          >
            {t("queue.assign", "Assign")}
          </Button>
        </RequirePermission>
      ) : (
        <Button
          size="xs"
          variant="light"
          onClick={() => handlers.onOpen(row.original.id)}
        >
          {t("queue.review", "Review")}
        </Button>
      ),
  };
}
