/// <reference path="../../lynx.d.ts" />
/**
 * Radio Component - Lynx 版 MUI Radio
 * 100% 一比一复刻 MUI Radio
 * 
 * 圆形单选按钮，使用 CSS 实现图标
 * 
 * 对应 MUI: packages/mui-material/src/Radio/Radio.js
 */
import './Radio.css'
import radioClasses, { getRadioUtilityClass } from './radioClasses'
export { radioClasses, getRadioUtilityClass }

// =============================================
// 类型定义
// =============================================

export type RadioColor = 'primary' | 'secondary' | 'default' | 'error' | 'info' | 'success' | 'warning'
export type RadioSize = 'small' | 'medium'

export interface RadioProps {
  /** 自定义类名 */
  className?: string
  /** 样式类覆盖 */
  classes?: Partial<typeof radioClasses>
  /** 是否选中 */
  checked?: boolean
  /** 选中图标 */
  checkedIcon?: any
  /** 默认是否选中 */
  defaultChecked?: boolean
  /** 是否禁用 */
  disabled?: boolean
  /** 是否禁用涟漪 */
  disableRipple?: boolean
  /** 未选中图标 */
  icon?: any
  /** ID 属性 */
  id?: string
  /** 传递给 input 元素的 props */
  inputProps?: Record<string, any>
  /** input 元素的 ref */
  inputRef?: any
  /** name 属性 */
  name?: string
  /** 是否必填 */
  required?: boolean
  /** 颜色 - 默认 primary */
  color?: RadioColor
  /** 尺寸 */
  size?: RadioSize
  /** 内联样式 */
  style?: Record<string, any>
  /** sx 属性 */
  sx?: Record<string, any>
  /** 值 */
  value?: string
  /** 点击事件 */
  bindtap?: (event?: any) => void
  onChange?: (event: any, checked: boolean) => void
}

// =============================================
// 辅助函数
// =============================================

function capitalize(str: string): string {
  return str.charAt(0).toUpperCase() + str.slice(1)
}

function composeClasses(
  slots: Record<string, (string | boolean | null | undefined)[]>,
  getUtilityClass: (slot: string) => string,
  classes?: Record<string, string>
): Record<string, string> {
  const output: Record<string, string> = {}
  
  Object.keys(slots).forEach((slot) => {
    output[slot] = slots[slot]
      .filter(Boolean)
      .map((key) => {
        if (classes && classes[key as string]) {
          return `${getUtilityClass(key as string)} ${classes[key as string]}`
        }
        return getUtilityClass(key as string)
      })
      .join(' ')
  })
  
  return output
}

// =============================================
// useUtilityClasses
// =============================================

interface OwnerState extends RadioProps {}

function useUtilityClasses(ownerState: OwnerState) {
  const { 
    classes, 
    checked, 
    disabled, 
    color = 'primary', 
    size = 'medium' 
  } = ownerState

  const slots = {
    root: [
      'root',
      checked && 'checked',
      disabled && 'disabled',
      color !== 'default' && `color${capitalize(color)}`,
      `size${capitalize(size)}`,
    ],
  }

  return composeClasses(slots, getRadioUtilityClass, classes)
}

// =============================================
// Radio 组件
// =============================================

export function Radio(props: RadioProps) {
  const {
    className,
    classes: classesProp,
    checked: checkedProp,
    defaultChecked = false,
    disabled = false,
    disableRipple = false,
    color = 'primary',
    size = 'medium',
    style,
    sx,
    value,
    bindtap,
    onChange,
    ...other
  } = props

  // 在 Lynx 环境下，组件必须是受控的
  // 如果没有提供 checked 属性，使用默认值
  const checked = checkedProp !== undefined ? checkedProp : defaultChecked

  const ownerState: OwnerState = {
    ...props,
    checked,
    disabled,
    color,
    size,
  }

  const classes = useUtilityClasses(ownerState)

  // 处理点击
  const handleTap = (event?: any) => {
    if (disabled) return

    // Radio 通常由 RadioGroup 控制，这里只触发回调
    if (bindtap) bindtap(event)
    if (onChange) onChange(event, true)
  }

  // 构建类名
  const rootClasses = [
    classes.root,
    radioClasses.root,
    className,
    checked && radioClasses.checked,
    disabled && radioClasses.disabled,
    color !== 'default' && radioClasses[`color${capitalize(color)}` as keyof typeof radioClasses],
    radioClasses[`size${capitalize(size)}` as keyof typeof radioClasses],
  ].filter(Boolean).join(' ')

  return (
    <view
      className={rootClasses}
      style={sx ? { ...sx, ...style } : style}
      bindtap={handleTap}
      accessibility-element={true}
      accessibility-role="radio"
      accessibility-checked={checked}
      accessibility-disabled={disabled}
      {...other}
    >
      {/* Radio 图标 - 使用 CSS 实现 */}
      <view className="MuiRadio-icon" />
    </view>
  )
}

export default Radio
