import type { JSX } from "preact";
import { cn } from "../../utils/cn.ts";
import { ComponentChildren } from "preact";

type ButtonVariant =
  | "primary" // zinc-900 background
  | "secondary" // zinc-200/800 background
  | "outline" // transparent with border
  | "success" // green
  | "danger" // red
  | "blue"; // blue

type ButtonSize = "sm" | "md" | "lg";

export interface ButtonProps
  extends Omit<JSX.IntrinsicElements["button"], "size"> {
  variant?: ButtonVariant;
  size?: ButtonSize;
  children: ComponentChildren;
  href?: string; // If provided, renders as a link styled like a button
}

const variantClasses = {
  primary:
    "bg-zinc-50 hover:bg-zinc-50/90 dark:bg-zinc-600 dark:hover:bg-zinc-600/90 text-zinc-900 dark:text-zinc-100 border border-zinc-200 dark:border-zinc-500/70",
  secondary:
    "bg-zinc-100 hover:bg-zinc-100/90 dark:bg-zinc-700 dark:hover:bg-zinc-700/90 text-zinc-900 dark:text-zinc-100 border border-zinc-200/70 dark:border-zinc-600/70",
  outline:
    "bg-transparent border border-zinc-300/70 hover:bg-zinc-50 dark:border-zinc-600/70 dark:hover:bg-zinc-600/10 text-zinc-900 dark:text-zinc-100",
  success:
    "bg-green-600 hover:bg-green-600/90 dark:bg-green-600 dark:hover:bg-green-600/90 text-white border border-green-700 dark:border-green-500",
  danger:
    "bg-red-600 hover:bg-red-600/90 dark:bg-red-600 dark:hover:bg-red-600/90 text-white border border-red-700 dark:border-red-500",
  blue: "bg-blue-600 hover:bg-blue-700 dark:bg-blue-600 dark:hover:bg-blue-700 text-white border border-blue-700 dark:border-blue-500",
};

const sizeClasses = {
  sm: "px-2.5 py-0.5 text-xs",
  md: "px-3 py-1 text-sm",
  lg: "px-4 py-2 text-sm font-medium",
};

export function Button(props: ButtonProps): JSX.Element {
  const {
    variant = "primary",
    size = "lg",
    children,
    href,
    className,
    ...rest
  } = props;

  const classes = cn(
    "rounded transition-colors inline-flex items-center font-medium",
    variantClasses[variant],
    sizeClasses[size],
    className
  );

  if (href) {
    return (
      <a href={href} class={classes}>
        {children}
      </a>
    );
  }

  return (
    <button class={classes} {...rest}>
      {children}
    </button>
  );
}
