import React, { useState, ReactChild, FunctionComponent } from 'react'
import onClickOutside from 'react-onclickoutside'

interface IDropdown {
  items?: {
    key: string | number
    title: string | ReactChild
    content: ReactChild
  }[]
  selectItem: (key: number | string) => void
}

const Dropdown: FunctionComponent<IDropdown> & {
  handleClickOutside?: () => void
} = ({ items, selectItem }: IDropdown) => {
  const [open, setOpen] = useState(false)
  const [active, setActive] = useState<undefined | string | number>()
  Dropdown.handleClickOutside = () => setOpen(false)

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

  return (
    <div id='dd-container'>
      <div id='dd-header'>
        <p onClick={event => setOpen(!open)}>
          {activeItem ? activeItem.title : 'please select one'}
        </p>
      </div>
      <ul id='dd-items'>
        {items &&
          items.map(item => (
            <li
              key={item.key}
              onClick={() => {
                setActive(item.key)
                selectItem(item.key)
                setOpen(false)
              }}
            >
              {typeof item.content === 'string' ? (
                <p className={active === item.key ? 'active' : undefined}>
                  {item.content}
                </p>
              ) : (
                item.content
              )}
            </li>
          ))}
      </ul>
      <div>{open ? 'open' : 'closed'}</div>
      <div>{active}</div>

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

        #dd-header p {
          background-color: #995555;
          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: #559955;
        }
      `}</style>
    </div>
  )
}

export default onClickOutside(Dropdown, {
  handleClickOutside: () => Dropdown.handleClickOutside
})
