/// <reference path="../../lynx.d.ts" />
/**
 * FormGroup Component - Lynx 版 MUI FormGroup
 * 100% 一比一复刻 MUI FormGroup
 * 
 * 为表单控件（Checkbox、Radio、Switch）提供分组容器
 * 
 * 对应 MUI: packages/mui-material/src/FormGroup/FormGroup.js
 */
import './FormGroup.css'
import formGroupClasses, { getFormGroupUtilityClass } from './formGroupClasses'
export { formGroupClasses, getFormGroupUtilityClass }

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

export interface FormGroupProps {
  /** 子元素 */
  children?: any
  /** 自定义类名 */
  className?: string
  /** 样式类覆盖 */
  classes?: Partial<typeof formGroupClasses>
  /** 是否错误状态 */
  error?: boolean
  /** 是否行排列 */
  row?: boolean
  /** 内联样式 */
  style?: Record<string, any>
  /** sx 属性 */
  sx?: Record<string, any>
}

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

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 FormGroupProps {}

function useUtilityClasses(ownerState: OwnerState) {
  const { classes, error, row } = ownerState

  const slots = {
    root: [
      'root',
      error && 'error',
      row && 'row',
    ],
  }

  return composeClasses(slots, getFormGroupUtilityClass, classes)
}

// =============================================
// FormGroup 组件
// =============================================

export function FormGroup(props: FormGroupProps) {
  const {
    children,
    className,
    classes: classesProp,
    error = false,
    row = false,
    style,
    sx,
    ...other
  } = props

  const ownerState: OwnerState = {
    ...props,
    error,
    row,
  }

  const classes = useUtilityClasses(ownerState)

  // 构建类名
  const rootClasses = [
    classes.root,
    className,
    error && 'MuiFormGroup-error',
    row && 'MuiFormGroup-row',
  ].filter(Boolean).join(' ')

  return (
    <view
      className={rootClasses}
      style={sx ? { ...sx, ...style } : style}
      {...other}
    >
      {children}
    </view>
  )
}

export default FormGroup
