import { useMemo } from 'react'

import { styled, vui } from '../core'
import { cs, filterUndefined } from '../utils'
import { CheckboxGroupProps } from './checkboxGroup.types'
import { CheckboxGroupProvider } from './context'

export const CheckboxGroupBase = styled.divBox`
  display: flex;
  flex-direction: column;
`

/**
 * Organizes layout and display of multiple checkboxes as a row or column.
 * Exposes some props to the children via context.
 */
export const CheckboxGroup = vui<'div', CheckboxGroupProps>((props, ref) => {
  const { className, defaultValue, disabled, isRow, name, onBlur, onChange, onFocus, size, variant, ...rest } = props

  const context = useMemo(
    () => filterUndefined({ defaultValue, disabled, name, onBlur, onChange, onFocus, size, variant }),
    [defaultValue, disabled, name, onBlur, onChange, onFocus, size, variant],
  )

  const aliasedProps = filterUndefined({
    flexDirection: isRow ? 'row' : undefined,
  } as const)

  return (
    <CheckboxGroupProvider value={context}>
      <CheckboxGroupBase className={cs('vui-checkboxGroup', className)} ref={ref} {...aliasedProps} {...rest} />
    </CheckboxGroupProvider>
  )
})

CheckboxGroup.displayName = 'CheckboxGroup'

export default CheckboxGroup
