import { cn } from "@/lib/utils";
import * as React from "react";

type Variant = "default" | "secondary";

export type ButtonProps = {
  href?: string;
  variant?: Variant;
  loading?: boolean;
  disabled?: boolean;
  className?: string;
  arrow?: boolean;
  children: React.ReactNode;
} & React.ButtonHTMLAttributes<HTMLButtonElement>;

const variantClasses: Record<Variant, string> = {
  default: "text-white bg-contigo-violeta",
  secondary: "bg-white text-contigo-violeta",
};

const base =
  "text-sm lg:text-base w-fit block transition-colors px-6 py-2.5 rounded-[3rem] font-semibold disabled:pointer-events-none disabled:opacity-30 hover:bg-contigo-verde hover:text-contigo-violeta-oscuro min-h-10";

const Spinner = ({ className }: { className?: string }) => (
  <svg
    className={cn("size-6 mr-2 animate-spin", className)}
    viewBox="0 0 24 24"
    fill="none"
    xmlns="http://www.w3.org/2000/svg"
    aria-hidden
  >
    <circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" opacity="0.2" />
    <path
      d="M22 12a10 10 0 00-10-10"
      stroke="currentColor"
      strokeWidth="4"
      strokeLinecap="round"
      strokeLinejoin="round"
    />
  </svg>
);

const Button = React.forwardRef<HTMLButtonElement | HTMLAnchorElement, ButtonProps>(
  ({ className, variant = "default", children, loading = false, href, disabled, arrow = true, ...props }, ref) => {
    const classes = cn(base, variantClasses[variant], className);
    const content = <>{loading ? <Spinner /> : <>{children}</>}</>;

    if (href) {
      return (
        <a
          ref={ref as React.Ref<HTMLAnchorElement>}
          className={classes}
          href={href}
          aria-disabled={disabled || loading}
          target="_blank"
          rel="noopener noreferrer"
          {...(props as React.AnchorHTMLAttributes<HTMLAnchorElement>)}
        >
          {content}
        </a>
      );
    }

    return (
      <button ref={ref as React.Ref<HTMLButtonElement>} className={classes} disabled={disabled || loading} {...props}>
        {content}
      </button>
    );
  }
);

Button.displayName = "Button";

export default Button;
