import { cva, type VariantProps } from "class-variance-authority";
import { forwardRef, type ButtonHTMLAttributes } from "react";
import { cn } from "@/lib/utils/cn";

const buttonVariants = cva(
  "inline-flex items-center justify-center gap-1.5 rounded-sm font-semibold transition-all duration-150 disabled:pointer-events-none disabled:opacity-50 active:scale-95",
  {
    variants: {
      variant: {
        primary:
          "bg-accent text-navy hover:bg-[#22b3ec] hover:-translate-y-px active:translate-y-0",
        outline:
          "border border-border bg-transparent text-primary hover:border-primary hover:bg-[#EFF6FF]",
        ghost:
          "border border-white/25 bg-transparent text-white hover:bg-white/10",
        dark: "bg-navy text-white hover:bg-navy-2",
        danger: "bg-danger text-white hover:bg-danger/90",
        icon: "border border-border bg-white text-muted hover:bg-[#F1F5F9]",
      },
      size: {
        sm: "px-3 py-1.5 text-xs rounded-[7px]",
        md: "px-[18px] py-2.5 text-sm rounded-sm",
        lg: "px-6 py-3 text-base",
        icon: "h-[34px] w-[34px] rounded-sm p-0",
        row: "h-7 w-7 rounded-md p-0",
      },
    },
    defaultVariants: {
      variant: "primary",
      size: "md",
    },
  }
);

function Spinner({ className }: { className?: string }) {
  return (
    <svg
      className={cn("animate-spin", className)}
      xmlns="http://www.w3.org/2000/svg"
      fill="none"
      viewBox="0 0 24 24"
    >
      <circle
        className="opacity-25"
        cx="12"
        cy="12"
        r="10"
        stroke="currentColor"
        strokeWidth="4"
      />
      <path
        className="opacity-75"
        fill="currentColor"
        d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
      />
    </svg>
  );
}

export interface ButtonProps
  extends ButtonHTMLAttributes<HTMLButtonElement>,
    VariantProps<typeof buttonVariants> {
  loading?: boolean;
}

export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
  ({ className, variant, size, loading, disabled, children, ...props }, ref) => (
    <button
      ref={ref}
      className={cn(buttonVariants({ variant, size }), className)}
      disabled={disabled ?? loading}
      {...props}
    >
      {loading && (
        <Spinner
          className={cn(
            "shrink-0",
            size === "sm" || size === "row" ? "h-3 w-3" : "h-4 w-4"
          )}
        />
      )}
      {children}
    </button>
  )
);
Button.displayName = "Button";
