import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
import { Loader2 } from "lucide-react";

const actionButtonVariants = cva(
  "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-[var(--radius)] text-sm font-medium transition-all duration-100 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:ring-2 focus-visible:ring-[var(--border-focus)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--bg-base)]",
  {
    variants: {
      variant: {
        primary:
          "bg-[var(--interactive-primary)] text-white shadow-[var(--shadow-sm)] hover:bg-[var(--interactive-primary-hover)] hover:shadow-[var(--shadow-md)]",
        secondary:
          "bg-[var(--interactive-secondary)] text-[var(--text-primary)] border border-[var(--border-default)] hover:bg-[var(--interactive-secondary-hover)]",
        danger:
          "bg-[var(--interactive-danger)] text-white shadow-[var(--shadow-sm)] hover:bg-[var(--interactive-danger-hover)]",
        ghost:
          "hover:bg-[var(--interactive-secondary)] hover:text-[var(--text-primary)] border border-transparent",
      },
      size: {
        sm: "h-8 px-3 text-xs gap-1.5",
        md: "h-10 px-4",
        lg: "h-12 px-6 text-base",
      },
    },
    defaultVariants: {
      variant: "primary",
      size: "md",
    },
  }
);

interface ActionButtonProps
  extends React.ButtonHTMLAttributes<HTMLButtonElement>,
    VariantProps<typeof actionButtonVariants> {
  asChild?: boolean;
  loading?: boolean;
}

export function ActionButton({
  className,
  variant,
  size,
  asChild = false,
  loading = false,
  disabled,
  children,
  ...props
}: ActionButtonProps) {
  const Comp = asChild ? Slot : "button";

  return (
    <Comp
      data-slot="action-button"
      className={cn(actionButtonVariants({ variant, size, className }))}
      disabled={disabled || loading}
      {...props}
    >
      {loading && <Loader2 className="animate-spin" size={16} />}
      {children}
    </Comp>
  );
}

export { actionButtonVariants };
