import * as React from 'react'

const { useEffect, useRef, useCallback } = React

export const Dropdown = (props: React.HTMLProps<HTMLSelectElement>) => {
  const dropdownRef = useRef<HTMLSelectElement>()

  useEffect(() => {
    const { current } = dropdownRef
    if (current) {
      const $select = $(current)
      $select.niceSelect()
      // jquery trigger doesn't trigger native handlers, so we gotta do it ourselves.
      $select.on('change', ($event) => {
        // don't recurse!!
        if (!$event.originalEvent) {
          $event.target.dispatchEvent(new Event('change', {
            bubbles: true
          }))
        }
      })
    }
    return () => {
      if (current) {
        const $select = $(current)
        $select.off('change')
        $select.niceSelect('destroy')
      }
    }
  }, [dropdownRef.current, props.value, props.children])

  return <select {...props} ref={dropdownRef} />
}

interface BooleanDropdownProps extends Omit<React.HTMLProps<HTMLSelectElement>, 'children' | 'value'> {
  value: boolean
}

export const BooleanDropdown = ({ value, onChange, ...props }: BooleanDropdownProps) => {
  const shadowedOnChange = useCallback((e: React.ChangeEvent<HTMLSelectElement>) => {
    const realValue = e.target.value === 't'
    const newTarget = {...e.target, value: realValue }

    onChange({...e, target: newTarget })
  }, [onChange])

  return (
    <Dropdown value={value ? 't' : 'f'} onChange={shadowedOnChange} {...props}>
      <option value="t">Yes</option>
      <option value="f">No</option>
    </Dropdown>
  )
}
