import { Link } from "@tanstack/react-router";
import type { LinkProps } from "@tanstack/react-router";
import { ArrowRight } from "lucide-react";
import { forwardRef } from "react";

type Variant = "solid" | "ghost" | "link";
type Size = "sm" | "md" | "lg";

const sizeMap: Record<Size, string> = {
  sm: "h-9 px-4 text-[10px]",
  md: "h-11 px-6 text-[11px]",
  lg: "h-12 px-8 text-[11px]",
};

const baseSolid = "inline-flex items-center justify-center gap-3 bg-brand-red text-white uppercase tracking-wider-x extralight border border-brand-red hover:bg-transparent hover:text-brand-red transition-colors duration-300";
const baseGhost = "inline-flex items-center justify-center gap-3 bg-transparent text-foreground uppercase tracking-wider-x extralight border border-border hover:border-brand-red hover:text-brand-red transition-colors duration-300";
const baseLink = "group inline-flex items-center gap-3 text-sm uppercase tracking-editorial extralight text-foreground hover:text-brand-red transition-colors";

type Common = {
  variant?: Variant;
  size?: Size;
  withArrow?: boolean;
  className?: string;
  children: React.ReactNode;
};

function cls(variant: Variant, size: Size, extra?: string) {
  if (variant === "link") return `${baseLink} ${extra ?? ""}`;
  const base = variant === "solid" ? baseSolid : baseGhost;
  return `${base} ${sizeMap[size]} ${extra ?? ""}`;
}

export const RegentButton = forwardRef<HTMLButtonElement, Common & React.ButtonHTMLAttributes<HTMLButtonElement>>(
  function RegentButton({ variant = "solid", size = "md", withArrow = false, className, children, ...rest }, ref) {
    return (
      <button ref={ref} className={cls(variant, size, className)} {...rest}>
        {variant === "link" && <span className="h-px w-10 bg-foreground group-hover:bg-brand-red group-hover:w-14 transition-all" />}
        {children}
        {withArrow && <ArrowRight className="w-4 h-4" />}
      </button>
    );
  }
);

export function RegentLinkButton(
  { variant = "solid", size = "md", withArrow = false, className, children, to, params, search, ...rest }:
    Common & LinkProps,
) {
  return (
    <Link to={to} params={params} search={search} className={cls(variant, size, className)} {...rest}>
      {variant === "link" && <span className="h-px w-10 bg-foreground group-hover:bg-brand-red group-hover:w-14 transition-all" />}
      {children}
      {withArrow && <ArrowRight className="w-4 h-4" />}
    </Link>
  );
}

export function RegentAnchor({
  variant = "solid", size = "md", withArrow = false, className, children, ...rest
}: Common & React.AnchorHTMLAttributes<HTMLAnchorElement>) {
  return (
    <a className={cls(variant, size, className)} {...rest}>
      {variant === "link" && <span className="h-px w-10 bg-foreground group-hover:bg-brand-red group-hover:w-14 transition-all" />}
      {children}
      {withArrow && <ArrowRight className="w-4 h-4" />}
    </a>
  );
}
