import React, {
  FC,
  KeyboardEvent,
  ReactNode,
  RefObject,
  useRef
} from 'react'

import { formatClassList } from '../../utils'


type CheckboxTypes = {
  children: ReactNode,
  size?: string,
  [other:string]: unknown
}

const INPUT: string = `
  cursor-pointer
  form-checkbox
  h-5
  w-5
  text-bscs-indigo-800
`

const TEXT: string = `
  text-sm
  ml-2
  text-bscs-gray-500
`

// Enter key not working on Chrome, maybe other browsers
const handleEnterKey = (
  e: KeyboardEvent,
  ref: RefObject<HTMLInputElement> | null
): void => {
  if (!ref || !ref.current) {
    return
  }

  if (document.activeElement === ref.current && e.key === 'Enter') {
    ref.current.checked = !ref.current.checked
  }
}

const Checkbox:FC<CheckboxTypes> = ({
  children,
  size='standard',
  ...other
}: CheckboxTypes) => {
  const ref: RefObject<HTMLInputElement> | null = useRef<HTMLInputElement>(null)

  const inputClassList = formatClassList(INPUT)
  const textClassList = formatClassList(TEXT)

  return (
    <div {...other}>
      <input
        className={inputClassList}
        type="checkbox"
        ref={ref}
        onKeyDown={(e: KeyboardEvent) => handleEnterKey(e, ref)}
      />
      <label className={textClassList}>{children}</label>
    </div>
  )
}

export default Checkbox
