/// <reference path="../../lynx.d.ts" />
/**
 * Switch Component - Lynx 版 MUI Switch
 * 100% 一比一复刻 MUI Switch
 * 
 * 开关组件，使用 CSS transition 实现滑动动画
 * 
 * 对应 MUI: packages/mui-material/src/Switch/Switch.js
 */
import './Switch.css'
import switchClasses, { getSwitchUtilityClass } from './switchClasses'
export { switchClasses, getSwitchUtilityClass }

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

export type SwitchColor = 'primary' | 'secondary' | 'default' | 'error' | 'info' | 'success' | 'warning'
export type SwitchSize = 'small' | 'medium'
export type SwitchEdge = 'start' | 'end'

export interface SwitchProps {
  /** 自定义类名 */
  className?: string
  /** 样式类覆盖 */
  classes?: Partial<typeof switchClasses>
  /** 是否选中 */
  checked?: boolean
  /** 默认是否选中 */
  defaultChecked?: boolean
  /** 是否禁用 */
  disabled?: boolean
  /** 是否禁用涟漪 */
  disableRipple?: boolean
  /** 边缘位置 */
  edge?: SwitchEdge
  /** ID 属性 */
  id?: string
  /** 传递给 input 元素的 props */
  inputProps?: Record<string, any>
  /** input 元素的 ref */
  inputRef?: any
  /** name 属性 */
  name?: string
  /** 是否必填 */
  required?: boolean
  /** 颜色 - 默认 primary */
  color?: SwitchColor
  /** 尺寸 */
  size?: SwitchSize
  /** 内联样式 */
  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 SwitchProps {}

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

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

  return composeClasses(slots, getSwitchUtilityClass, classes)
}

// =============================================
// Switch 组件
// =============================================

export function Switch(props: SwitchProps) {
  const {
    className,
    classes: classesProp,
    checked: checkedProp,
    defaultChecked = false,
    disabled = false,
    disableRipple = false,
    edge,
    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,
    edge,
  }

  const classes = useUtilityClasses(ownerState)

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

    const newChecked = !checked

    // 触发回调
    if (bindtap) bindtap(event)
    if (onChange) onChange(event, newChecked)
  }

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

  const switchBaseClasses = [
    classes.switchBase,
    switchClasses.switchBase,
    checked && switchClasses.checked,
    disabled && switchClasses.disabled,
  ].filter(Boolean).join(' ')

  return (
    <view
      className={rootClasses}
      style={sx ? { ...sx, ...style } : style}
      {...other}
    >
      <view
        className={switchBaseClasses}
        bindtap={handleTap}
        accessibility-element={true}
        accessibility-role="switch"
        accessibility-checked={checked}
        accessibility-disabled={disabled}
      >
        <view className={classes.input} />
        <view className={classes.thumb} />
      </view>
      <view className={classes.track} />
    </view>
  )
}

export default Switch
