import type {
  ButtonHTMLAttributes,
  LabelHTMLAttributes,
  ReactNode,
} from 'react';

import {
  getPlatformActionButtonClassName,
  type PlatformActionButtonAlign,
  type PlatformActionButtonShape,
  type PlatformActionButtonSize,
  type PlatformActionButtonSurface,
  type PlatformActionButtonTone,
} from './platformActionButtonModel';

type PlatformActionButtonBaseProps = {
  children: ReactNode;
  tone?: PlatformActionButtonTone;
  surface?: PlatformActionButtonSurface;
  size?: PlatformActionButtonSize;
  shape?: PlatformActionButtonShape;
  align?: PlatformActionButtonAlign;
  fullWidth?: boolean;
};

type PlatformActionButtonButtonProps = Omit<
  ButtonHTMLAttributes<HTMLButtonElement>,
  'children'
> &
  PlatformActionButtonBaseProps & {
    asChild?: false;
  };

type PlatformActionButtonLabelProps = Omit<
  LabelHTMLAttributes<HTMLLabelElement>,
  'children'
> &
  PlatformActionButtonBaseProps & {
    asChild: 'label';
  };

type PlatformActionButtonProps =
  | PlatformActionButtonButtonProps
  | PlatformActionButtonLabelProps;

/**
 * 平台通用动作按钮。
 * 收口平台与个人中心主动作按钮的样式族、尺寸、圆角和禁用态 class。
 */
export function PlatformActionButton({
  children,
  tone = 'primary',
  surface = 'platform',
  size = 'sm',
  shape = 'default',
  align = 'center',
  fullWidth = false,
  className,
  asChild,
  ...buttonProps
}: PlatformActionButtonProps) {
  const actionClassName = [
    getPlatformActionButtonClassName({
      surface,
      tone,
      size,
      shape,
      align,
      fullWidth,
    }),
    className,
  ]
    .filter(Boolean)
    .join(' ');

  if (asChild === 'label') {
    return (
      <label
        {...(buttonProps as LabelHTMLAttributes<HTMLLabelElement>)}
        className={actionClassName}
      >
        {children}
      </label>
    );
  }

  const { type = 'button', ...restButtonProps } =
    buttonProps as ButtonHTMLAttributes<HTMLButtonElement>;

  return (
    <button {...restButtonProps} type={type} className={actionClassName}>
      {children}
    </button>
  );
}
