import type { MouseEvent, ReactNode } from "react";
import Button from "../Button";
import { usePlatformLanguage } from "../../i18n/LanguageContext";

export type TableActionDefinition = {
  id: string;
  label: string;
  icon: ReactNode;
  onClick: () => void;
  /**
   * @deprecated Use `disabled` for a row-level unavailable state and omit the
   * action from the array only when it is not part of this table's action set.
   * A false value is retained as a disabled, visible action for compatibility.
   */
  applicable?: boolean;
  disabled?: boolean;
  disabledReason?: ReactNode;
  variant?: "primary" | "secondary" | "ghost" | "danger";
};

export type TableActionGroupProps = {
  actions: readonly (TableActionDefinition | false | null | undefined)[];
  label?: string;
  className?: string;
  /** Reserve trailing action slots so controls keep the same column position. */
  minimumSlots?: number;
};

function isDefinedAction(
  action: TableActionDefinition | false | null | undefined
): action is TableActionDefinition {
  return Boolean(action);
}

export function runTableAction(
  event: Pick<MouseEvent<HTMLButtonElement>, "stopPropagation">,
  onClick: () => void
) {
  event.stopPropagation();
  onClick();
}

/**
 * The standard row-level action surface for tables and DataGrids.
 *
 * Callers define the action set for the whole table. An action that cannot be
 * used for one row stays visible and disabled; an action that is structurally
 * irrelevant to the table is omitted from the array. Labels remain available
 * to assistive technology and as native tooltips while the visible controls
 * stay icon-only. `minimumSlots` reserves trailing positions for empty-state
 * rows, keeping their first action aligned with ordinary rows.
 */
export default function TableActionGroup({
  actions,
  label = "i18n:govoplan-core.actions.c3cd636a",
  className = "",
  minimumSlots = 0
}: TableActionGroupProps) {
  const { translateText } = usePlatformLanguage();
  const definedActions = actions.filter(isDefinedAction);
  if (definedActions.length === 0) return null;
  const normalizedMinimumSlots = Number.isFinite(minimumSlots) ? Math.max(0, Math.floor(minimumSlots)) : 0;
  const placeholderCount = Math.max(0, normalizedMinimumSlots - definedActions.length);

  return (
    <div
      className={`table-action-group${className ? ` ${className}` : ""}`}
      role="group"
      aria-label={translateText(label)}
    >
      {definedActions.map((action) => {
        const translatedLabel = translateText(action.label);
        return (
          <Button
            key={action.id}
            type="button"
            variant={action.variant ?? "secondary"}
            className="table-action-button"
            aria-label={translatedLabel}
            title={translatedLabel}
            disabled={action.disabled || action.applicable === false}
            disabledReason={action.disabledReason}
            onClick={(event) => runTableAction(event, action.onClick)}
          >
            <span className="table-action-icon" aria-hidden="true">
              {action.icon}
            </span>
          </Button>
        );
      })}
      {Array.from({ length: placeholderCount }, (_unused, index) => (
        <span
          key={`reserved-action-slot-${index}`}
          className="table-action-placeholder"
          aria-hidden="true"
        />
      ))}
    </div>
  );
}
