import type { ButtonHTMLAttributes, ReactNode } from "react";
import { IconSpinner } from "@/components/icons";

type Variant = "primary" | "secondary" | "ghost" | "danger";
type Size = "sm" | "md";

type Props = ButtonHTMLAttributes<HTMLButtonElement> & {
  variant?: Variant;
  size?: Size;
  loading?: boolean;
  icon?: ReactNode;
  iconRight?: ReactNode;
};

const VARIANT: Record<Variant, string> = {
  primary:
    "bg-accent text-accent-foreground hover:bg-accent-hover active:bg-accent-active shadow-sm",
  secondary:
    "bg-surface text-foreground border border-border-strong hover:bg-surface-2 active:bg-surface-3",
  ghost: "text-foreground hover:bg-surface-2 active:bg-surface-3",
  danger:
    "bg-danger text-white hover:bg-red-700 active:bg-red-800 shadow-sm",
};

const SIZE: Record<Size, string> = {
  sm: "h-8 px-3 text-xs gap-1.5 rounded-md",
  md: "h-9 px-4 text-sm gap-2 rounded-md",
};

export function Button({
  variant = "primary",
  size = "md",
  loading = false,
  icon,
  iconRight,
  children,
  className = "",
  disabled,
  ...rest
}: Props) {
  const isDisabled = disabled || loading;
  return (
    <button
      {...rest}
      disabled={isDisabled}
      className={[
        "inline-flex items-center justify-center font-medium",
        "transition-all duration-150",
        "disabled:opacity-50 disabled:cursor-not-allowed",
        "focus-visible:outline-2 focus-visible:outline-accent-ring focus-visible:outline-offset-2",
        VARIANT[variant],
        SIZE[size],
        className,
      ].join(" ")}
    >
      {loading ? <IconSpinner size={size === "sm" ? 14 : 16} /> : icon}
      {children}
      {iconRight}
    </button>
  );
}
