import { forwardRef, memo, useCallback, useImperativeHandle } from 'react'
import MCheckbox from '@/components/checkbox'
import type { ColorType, ProductType } from '@/context/ContextShop'
import { useCurrenShop } from '@/context/ContextShop'

interface ParamType {
  colorItem: ColorType
}
interface IndexType {
  onSelect?: (val: boolean) => void
  checkStatus: boolean
}
export default memo(forwardRef((props: ParamType, ref) => {
  const { colorItem } = props
  const { state, dispatch } = useCurrenShop()
  const indexs = colorItem.index_str.split(',')
  const onSelect = useCallback((status) => {
    state.list[indexs[0]].color_list[indexs[1]].checked = !state.list[indexs[0]].color_list[indexs[1]].checked
    const tf = state.list[indexs[0]].color_list.some(item => item.checked)
    state.list[indexs[0]].checked = tf
    dispatch({ type: 'updateProduct', data: { list: state.list } })
  }, [state.list[indexs[0]].color_list[indexs[1]].checked])
  useImperativeHandle(ref, () => ({
    onSelect,
  }))
  return <Index checkStatus={state.list[indexs[0]].color_list[indexs[1]].checked} onSelect={onSelect} />
}))

const Index = memo((props: IndexType) => {
  const { checkStatus, onSelect } = props
  const setSelect = (status) => {
    onSelect?.(status)
  }
  return <MCheckbox status={checkStatus} onSelect={() => setSelect(true)} onClose={() => setSelect(false)} />
})
