import { type ButtonHTMLAttributes, forwardRef } from "react";
import { clsx } from "clsx";

interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
  variant?: "primary" | "secondary" | "ghost" | "danger";
  size?: "sm" | "md" | "lg";
  loading?: boolean;
}

export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
  ({ variant = "primary", size = "md", loading, className, children, disabled, ...props }, ref) => {
    return (
      <button
        ref={ref}
        disabled={disabled || loading}
        className={clsx(
          "inline-flex items-center justify-center font-medium rounded-[10px] transition-all duration-150",
          "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#0071e3]/40",
          "disabled:opacity-50 disabled:cursor-not-allowed select-none",
          variant === "primary" &&
            "bg-[#0071e3] text-white hover:bg-[#0077ed] active:bg-[#006edb] shadow-sm",
          variant === "secondary" &&
            "bg-black/5 text-[#1d1d1f] hover:bg-black/10 active:bg-black/[0.15] border border-black/[0.08]",
          variant === "ghost" &&
            "text-[#0071e3] hover:bg-[#0071e3]/8 active:bg-[#0071e3]/12",
          variant === "danger" &&
            "bg-red-500 text-white hover:bg-red-600 active:bg-red-700 shadow-sm",
          size === "sm" && "text-[13px] px-3 h-7 gap-1.5",
          size === "md" && "text-[14px] px-4 h-9 gap-2",
          size === "lg" && "text-[15px] px-5 h-11 gap-2",
          className,
        )}
        {...props}
      >
        {loading && (
          <svg
            className="animate-spin -ml-0.5 h-4 w-4"
            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>
        )}
        {children}
      </button>
    );
  },
);
Button.displayName = "Button";