import { memo, useEffect, useRef } from "react"

export const enum CheckboxState {
  Checked,
  Empty,
  Indeterminate,
}

export const TristateCheckbox: React.FC<
  Omit<React.InputHTMLAttributes<HTMLInputElement>, "type" | "ref" | "checked"> & {
    checked: CheckboxState
  }
> = memo(({ checked, ...props }) => {
  const ref = useRef<HTMLInputElement>(null)

  useEffect(() => {
    const input = ref.current
    if (!input) {
      return
    }

    if (checked === CheckboxState.Checked) {
      input.checked = true
      input.indeterminate = false
    } else if (checked === CheckboxState.Empty) {
      input.checked = false
      input.indeterminate = false
    } else if (checked === CheckboxState.Indeterminate) {
      input.checked = false
      input.indeterminate = true
    }
  }, [checked])

  return <input ref={ref} type="checkbox" {...props} />
})
