/**
 * V21 Button 按钮
 * 封装 Ant Design Button，应用 V21 设计系统样式
 */
import React from "react"
import { Button as AntButton } from "antd"
import type { ButtonProps as AntButtonProps } from "antd"
import classNames from "classnames"
import "./ui.css"

export type ButtonType = "primary" | "secondary" | "ghost" | "text" | "danger" | "link"

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

export interface ButtonProps extends Omit<AntButtonProps, "type" | "size"> {
  /** 按钮类型 */
  buttonType?: ButtonType
  /** 按钮尺寸 */
  buttonSize?: ButtonSize
  /** 兼容 antd type（用于直接替换） */
  type?: AntButtonProps["type"]
  /** 兼容 antd size */
  size?: AntButtonProps["size"]
}

const TYPE_CLASS_MAP: Record<ButtonType, string> = {
  primary: "xx-btn-primary",
  secondary: "xx-btn-secondary",
  ghost: "xx-btn-ghost",
  text: "xx-btn-text",
  danger: "xx-btn-danger",
  link: "xx-btn-link",
}

const SIZE_CLASS_MAP: Record<ButtonSize, string> = {
  sm: "xx-btn-sm",
  md: "xx-btn-md",
  lg: "xx-btn-lg",
}

/** 将 buttonType 映射到 antd type */
const toAntdType = (bt: ButtonType): AntButtonProps["type"] => {
  switch (bt) {
    case "primary":
      return "primary"
    case "danger":
      return "primary"
    case "link":
      return "link"
    case "text":
      return "text"
    default:
      return "default"
  }
}

const Button: React.FC<ButtonProps> = ({
  buttonType = "ghost",
  buttonSize = "md",
  className,
  children,
  type,
  size,
  ...rest
}) => {
  const antdType = type ?? toAntdType(buttonType)
  const antdSize =
    size ?? (buttonSize === "sm" ? "small" : buttonSize === "lg" ? "large" : "middle")

  const v21Class = classNames(
    "xx-btn",
    TYPE_CLASS_MAP[buttonType],
    SIZE_CLASS_MAP[buttonSize],
    className,
  )

  return (
    <AntButton
      type={antdType}
      size={antdSize}
      className={v21Class}
      danger={buttonType === "danger" ? true : rest.danger}
      {...rest}
    >
      {children}
    </AntButton>
  )
}

export default Button
