import { Link } from "@tanstack/react-router";
import type { ButtonHTMLAttributes, ReactNode } from "react";
import { cn } from "@/lib/utils";

const variants = {
  primary:
    "bg-ivory text-ink hover:bg-ivory-dim border border-transparent",
  gold: "bg-gold text-ink hover:bg-beige border border-transparent",
  outline:
    "bg-transparent text-ivory border border-gold/50 hover:border-gold hover:bg-ivory/5",
  ghost: "bg-transparent text-ivory/80 hover:text-ivory border border-transparent",
  ink: "bg-ink text-ivory hover:bg-ink-soft border border-transparent",
};

const sizes = {
  sm: "h-10 px-5 text-xs tracking-[0.18em] uppercase",
  md: "h-12 px-7 text-[0.7rem] tracking-[0.2em] uppercase",
  lg: "h-14 px-9 text-[0.75rem] tracking-[0.22em] uppercase",
};

type Props = ButtonHTMLAttributes<HTMLButtonElement> & {
  to?: string;
  params?: Record<string, string>;
  search?: Record<string, string | undefined>;
  href?: string;
  variant?: keyof typeof variants;
  size?: keyof typeof sizes;
  children: ReactNode;
};

export function Button({
  to,
  params,
  search,
  href,
  variant = "primary",
  size = "md",
  className,
  children,
  ...props
}: Props) {
  const cls = cn(
    "inline-flex items-center justify-center gap-2 rounded-full font-sans font-medium",
    "transition-[transform,background-color,border-color,color,opacity] duration-150 ease-out",
    "active:not-disabled:scale-[0.96] disabled:opacity-50 disabled:pointer-events-none",
    variants[variant],
    sizes[size],
    className,
  );

  if (to) {
    return (
      <Link
        to={to}
        params={params as never}
        search={search as never}
        className={cls}
      >
        {children}
      </Link>
    );
  }
  if (href) {
    return (
      <a href={href} className={cls}>
        {children}
      </a>
    );
  }
  return (
    <button type="button" className={cls} {...props}>
      {children}
    </button>
  );
}
