"use client";

import { forwardRef } from "react";
import type { ReactNode } from "react";
import { Loader2 } from "lucide-react";
import { Button, type ButtonProps } from "@/components/ui/button";
import { cn } from "@/lib/utils";

/**
 * Page/toolbar action button.
 *
 * Presentation comes entirely from the shadcn `Button` primitive; this wrapper
 * only adds the toolbar conventions the app repeats everywhere — a leading
 * icon, a busy state that swaps in a spinner and an alternate label, and an
 * optional label that collapses to icon-only on small screens.
 *
 * It replaces the button class string that had been copy-pasted into 26
 * separate `*Actions.tsx` files, where it had drifted into four paddings, two
 * font weights and three different disabled treatments.
 */

type ActionButtonVariant = "primary" | "secondary" | "ghost" | "danger";

/** Maps this component's product-facing names onto shadcn Button variants. */
const VARIANT_MAP: Record<ActionButtonVariant, ButtonProps["variant"]> = {
  primary: "default",
  secondary: "outline",
  ghost: "ghost",
  danger: "destructive",
};

export interface ActionButtonProps
  extends Omit<ButtonProps, "children" | "variant" | "size"> {
  /** Leading icon — pass the bare lucide component; it is sized for you. */
  icon?: ReactNode;
  children?: ReactNode;
  variant?: ActionButtonVariant;
  size?: "sm" | "md";
  /** Shows a spinner in place of the icon and disables the button. */
  loading?: boolean;
  /** Label swapped in while `loading` is true, e.g. "Refreshing…". */
  loadingLabel?: string;
  /** Collapse to an icon-only target below `sm`. */
  hideLabelOnMobile?: boolean;
}

export const ActionButton = forwardRef<HTMLButtonElement, ActionButtonProps>(
  function ActionButton(
    {
      icon,
      children,
      variant = "secondary",
      size = "sm",
      loading = false,
      loadingLabel,
      hideLabelOnMobile = false,
      className,
      disabled,
      type = "button",
      ...rest
    },
    ref
  ) {
    const isDisabled = disabled || loading;
    const label = loading && loadingLabel ? loadingLabel : children;

    return (
      <Button
        ref={ref}
        type={type}
        variant={VARIANT_MAP[variant]}
        size={size === "sm" ? "sm" : "default"}
        disabled={isDisabled}
        aria-busy={loading || undefined}
        className={cn("gap-1.5", className)}
        {...rest}
      >
        {loading ? (
          <Loader2 className="size-4 shrink-0 animate-spin" aria-hidden />
        ) : (
          icon && (
            <span className="shrink-0 [&>svg]:size-4" aria-hidden>
              {icon}
            </span>
          )
        )}
        {label && (
          <span className={cn(hideLabelOnMobile && "sr-only sm:not-sr-only")}>
            {label}
          </span>
        )}
      </Button>
    );
  }
);
