import { useState, FunctionComponent, useRef } from 'react'
import { useOnClickOutside } from '../../lib/onClickOutside'
import { customEvent } from '../../lib/customEvent'

export interface IDropdown {
  items?: IDropdownItem[]
  name: string
  value: string
  onChange: (event: CustomChangeEvent) => void
}

export interface IDropdownItem {
  key: string | number
  title: string
}

const Dropdown: FunctionComponent<IDropdown> = ({
  items = [],
  name,
  value,
  onChange,
  children,
}) => {
  const [open, setOpen] = useState(false)
  const [active, setActive] = useState<undefined | IDropdownItem>()
  const ref = useRef<HTMLDivElement>(null)
  useOnClickOutside(ref, () => setOpen(false))

  const activeItem = active && items?.find((item) => item.key === active.key)

  return (
    <div id='dd-container' ref={ref}>
      <div id='dd-header' onClick={() => setOpen(!open)}>
        {activeItem ? activeItem.title : 'please select one'}
      </div>
      <ul id='dd-items'>{items}</ul>
      <div>{open ? 'open' : 'closed'}</div>
      <div>{active}</div>

      <style jsx>{`
        #dd-container {
          position: relative;
          margin: 0;
          padding: 0;
        }

        #dd-header p {
          background-color: #99555533;
          margin: 0;
          padding: 0;
        }

        #dd-items {
          display: ${open ? 'block' : 'none'};
          position: absolute;
          width: 100%;
          max-height: 300px;
          z-index: 5;
          overflow-y: scroll;
          margin: 0;
          padding: 0;
          background-color: #55995533;
        }
      `}</style>
    </div>
  )
}

export default Dropdown
