import React, {useEffect, useState} from 'react'
import classnames from 'classnames'
import './index.less'

type Props = {
  checked: boolean
  disable?: boolean
  className?: string
  item?: any
  type?: 'free' | 'join'
  onClick?(isCheck: boolean, item?: any, type?: string): void
}

const Switch: React.FC<Props> = (props: Props) => {
  const {className, disable, checked, item, type} = props
  const [switchClassName, setSwitchClassName] = useState('')
  useEffect(() => {
    setSwitchClassName(`switch-handle ${checked ? 'checked' : 'unchecked'}`)
  }, [])
  useEffect(() => {
    if (switchClassName) {
      setSwitchClassName(`switch-handle ${checked ? 'active-on' : 'active-off'}`)
    }
  }, [checked])
  const newClassName = classnames('switch', className, {disable, check: checked})
  const onClickSwitch = (isCheck: boolean) => {
    if (disable) return
    props?.onClick?.(isCheck, item, type)
  }
  return (
    <div className={newClassName} onClick={() => onClickSwitch(!checked)}>
      <div className={switchClassName} />
    </div>
  )
}

export default Switch
