import * as React from "react";
import {
  Button as KumoButton,
  LinkButton as KumoLinkButton,
  type ButtonProps as KumoButtonProps,
  type LinkButtonProps as KumoLinkButtonProps,
} from "@cloudflare/kumo/components/button";

type ButtonVariant = "default" | "secondary" | "outline" | "ghost" | "destructive";
type ButtonSize = "default" | "sm" | "lg" | "icon";

const variantMap: Record<ButtonVariant, KumoButtonProps["variant"]> = {
  default: "primary",
  secondary: "secondary",
  outline: "outline",
  ghost: "ghost",
  destructive: "destructive",
};

const sizeMap: Record<ButtonSize, KumoButtonProps["size"]> = {
  default: "base",
  sm: "sm",
  lg: "lg",
  icon: "base",
};

export type ButtonProps = Omit<KumoButtonProps, "variant" | "size" | "shape"> & {
  variant?: ButtonVariant;
  size?: ButtonSize;
};

export type LinkButtonProps = Omit<KumoLinkButtonProps, "variant" | "size"> & {
  variant?: ButtonVariant;
  size?: Exclude<ButtonSize, "icon">;
};

export const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(function Button(
  { variant = "default", size = "default", ...props },
  ref,
): React.ReactElement {
  const kumoProps = {
    ref,
    shape: size === "icon" ? "square" : "base",
    size: sizeMap[size],
    variant: variantMap[variant],
    ...props,
  } as KumoButtonProps & React.RefAttributes<HTMLButtonElement>;

  return (
    <KumoButton {...kumoProps} />
  );
});

export const LinkButton = React.forwardRef<HTMLAnchorElement, LinkButtonProps>(function LinkButton(
  { variant = "default", size = "default", ...props },
  ref,
): React.ReactElement {
  return <KumoLinkButton ref={ref} size={sizeMap[size]} variant={variantMap[variant]} {...props} />;
});
