import Link from "next/link";
import type { ReactNode } from "react";
import { ArrowRight } from "@/components/ui/Icons";
import { cn } from "@/lib/cn";

type Variant = "primary" | "secondary";
type Tone = "light" | "dark";
type Size = "sm" | "md" | "lg";

const variantClasses: Record<Tone, Record<Variant, string>> = {
  light: {
    primary: "bg-signal text-white [--btn-fill:var(--color-ink)]",
    secondary: "border border-line-strong text-ink [--btn-fill:var(--color-paper-deep)]",
  },
  dark: {
    primary: "bg-paper text-ink hover:text-white focus-visible:text-white [--btn-fill:var(--color-signal)]",
    secondary: "border border-night-muted/50 text-night-text [--btn-fill:var(--color-night-raised)]",
  },
};

const sizeClasses: Record<Size, string> = {
  sm: "h-10 px-4 text-sm gap-2",
  md: "h-12 px-5 text-[0.9375rem] gap-2.5",
  lg: "h-14 px-6 text-base gap-3",
};

interface ButtonLinkProps {
  href: string;
  children: ReactNode;
  variant?: Variant;
  tone?: Tone;
  size?: Size;
  arrow?: boolean;
  block?: boolean;
  className?: string;
}

export function buttonClassName({
  variant = "primary",
  tone = "light",
  size = "md",
  block,
  className,
}: Omit<ButtonLinkProps, "href" | "children" | "arrow">) {
  return cn(
    "btn inline-flex shrink-0 items-center justify-center whitespace-nowrap rounded-md font-medium tracking-[-0.005em]",
    variantClasses[tone][variant],
    sizeClasses[size],
    block && "w-full sm:w-auto",
    className,
  );
}

export function ButtonLink({ href, children, variant, tone, size, arrow = true, block, className }: ButtonLinkProps) {
  return (
    <Link href={href} className={buttonClassName({ variant, tone, size, block, className })}>
      <span className="btn-fill" aria-hidden="true" />
      <span>{children}</span>
      {arrow ? <ArrowRight className="btn-arrow" size={16} /> : null}
    </Link>
  );
}

interface TextLinkProps {
  href: string;
  children: ReactNode;
  tone?: Tone;
  className?: string;
}

export function TextLink({ href, children, tone = "light", className }: TextLinkProps) {
  return (
    <Link
      href={href}
      className={cn(
        "link-arrow group inline-flex min-h-11 items-center gap-2 font-medium",
        tone === "dark" ? "text-night-text" : "text-ink",
        className,
      )}
    >
      <span className="link-underline">{children}</span>
      <ArrowRight className="btn-arrow" size={15} />
    </Link>
  );
}
