import type { ButtonHTMLAttributes, ComponentProps, ReactNode } from "react";
import Link from "next/link";
import { cn } from "@/lib/cn";

const sizes = {
  default: "h-11 max-h-11 px-5 text-sm",
  sm: "h-9 max-h-9 px-3.5 text-[0.8125rem]",
} as const;

const variants = {
  primary: "bg-accent text-white hover:bg-accent-hover",
  secondary: "border border-line text-primary hover:border-primary",
  inverse: "bg-surface text-primary",
  ghost: "border border-white/40 text-white hover:border-white",
} as const;

type Variant = keyof typeof variants;
type Size = keyof typeof sizes;

const base =
  "inline-flex items-center justify-center gap-1.5 rounded-pv font-semibold transition focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent disabled:cursor-not-allowed disabled:opacity-70";

type LinkProps = {
  href: string;
  variant?: Variant;
  size?: Size;
  className?: string;
  children: ReactNode;
} & Omit<ComponentProps<typeof Link>, "href" | "className" | "children">;

type NativeButton = {
  href?: undefined;
  variant?: Variant;
  size?: Size;
  className?: string;
  children: ReactNode;
} & ButtonHTMLAttributes<HTMLButtonElement>;

export function Button(props: LinkProps | NativeButton) {
  const variant = props.variant ?? "primary";
  const size = props.size ?? "default";
  const classes = cn(base, sizes[size], variants[variant], props.className);

  if ("href" in props && props.href) {
    const { href, variant: _variant, size: _size, className: _className, children, ...rest } = props;
    return (
      <Link href={href} className={classes} {...rest}>
        {children}
      </Link>
    );
  }

  const {
    variant: _variant,
    size: _size,
    className: _className,
    children,
    href: _href,
    ...rest
  } = props as NativeButton;

  return (
    <button className={classes} type="button" {...rest}>
      {children}
    </button>
  );
}
