import { View } from '@tarojs/components'
import classnames from 'classnames'
import { forwardRef, useEffect, useImperativeHandle, useState } from 'react'
import IconFont from '../iconfont'
import styles from './index.module.scss'

type CheckboxSize = 'normal' | 'small'

type params = {
  onSelect?: () => void //选择触发
  onClose?: () => void //取消触发
  status?: boolean //是否选中
  disabled?: boolean //是否禁用
  circle?: boolean
  round?: boolean
  size?: CheckboxSize
}
export default forwardRef((props: params, ref) => {
  const { onSelect, onClose, status = false, disabled = false, circle = false, round = true, size = 'normal' } = props
  const [selected, SetSelected] = useState(false)
  const onSelectEven = () => {
    if (disabled) return false
    let res = !selected
    if (res) {
      onSelect?.()
    } else {
      onClose?.()
    }
    SetSelected(res)
  }

  const getMainClassName = () => {
    const classObject = {
      [styles['checkbox_main--selected']]: selected,
      [styles[`checkbox_main--${size}`]]: size,
      [styles['checkbox_main--round']]: round,
      [styles['checkbox_main--circle']]: circle,
    }
    return classObject
  }

  const getClassName = () => {
    const classObject = {
      [styles.no_checkbox_item]: disabled,
      [styles.checkbox_item_select]: selected,
    }
    return classObject
  }

  useImperativeHandle(ref, () => ({
    onSelectEven,
  }))
  useEffect(() => {
    SetSelected(status)
  }, [status])
  return (
    <>
      <View className={classnames(styles.checkbox_main, getMainClassName())} onClick={() => onSelectEven()}>
        <View className={classnames(styles.checkbox_item, getClassName())}>
          {selected && <IconFont name='icon-a-jizhumima' size={22} color='#fff'></IconFont>}
        </View>
      </View>
    </>
  )
})
