import { JSX, ParentComponent, splitProps } from "solid-js";

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

export const Button: ParentComponent<ButtonProps> = (props) => {
  const [local, rest] = splitProps(props, [
    "variant",
    "size",
    "isLoading",
    "fullWidth",
    "children",
    "class",
  ]);

  const variantClasses = {
    primary: "btn-primary",
    secondary: "btn-secondary",
    ghost: "btn-ghost",
    danger: "bg-error text-white border-error hover:bg-error-hover",
  };

  const sizeClasses = {
    sm: "px-4 py-2 text-sm",
    md: "px-5 py-2.5 text-[0.9375rem]",
    lg: "px-6 py-3 text-base",
  };

  const baseClasses = [
    "inline-flex items-center justify-center gap-2 rounded-button font-display font-medium tracking-tight transition-all duration-200",
    "disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:transform-none",
    "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/50",
    variantClasses[local.variant || "primary"],
    sizeClasses[local.size || "md"],
    local.fullWidth ? "w-full" : "",
    local.class || "",
  ].join(" ");

  return (
    <button
      {...rest}
      class={baseClasses}
      disabled={rest.disabled || local.isLoading}
    >
      {local.isLoading && (
        <svg
          class="animate-spin h-4 w-4"
          xmlns="http://www.w3.org/2000/svg"
          fill="none"
          viewBox="0 0 24 24"
        >
          <circle
            class="opacity-25"
            cx="12"
            cy="12"
            r="10"
            stroke="currentColor"
            stroke-width="4"
          />
          <path
            class="opacity-75"
            fill="currentColor"
            d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
          />
        </svg>
      )}
      {local.children}
    </button>
  );
};
