import {useRef, useEffect, useState} from 'react'
import {useRouter} from 'next/router'
import PropTypes from 'prop-types'

import {
  Button,
  ClickAwayListener,
  Grow,
  MenuItem,
  MenuList,
  Paper,
  Popper,
  Badge
} from '@material-ui/core'

import {makeStyles} from '@material-ui/core/styles'
import MenuBookIcon from '@material-ui/icons/MenuBook'

const useStyles = makeStyles(theme => ({
  root: {
    display: 'flex'
  },
  paper: {
    marginRight: theme.spacing(2)
  }
}))

export default function MizikBadjMeni({teks}) {
  const classes = useStyles()
  const [open, setOpen] = useState(false)
  const anchorRef = useRef(null)
  const router = useRouter()

  const handleToggle = () => {
    setOpen(previousOpen_ => !previousOpen_)
  }

  const handleClose = event => {
    if (anchorRef.current && anchorRef.current.contains(event.target)) {
      return
    }

    setOpen(false)
  }

  const handleClick = slug => {
    router.push(`/teks/${slug}#${slug}`).then(() => window.scrollTo(0, 0))
  }

  function handleListKeyDown(event) {
    if (event.key === 'Tab') {
      event.preventDefault()
      setOpen(false)
    }
  }

  const previousOpen = useRef(open)
  useEffect(() => {
    if (previousOpen.current === true && open === false) {
      anchorRef.current.focus()
    }

    previousOpen.current = open
  }, [open])

  return (
    <div className={classes.root}>
      <Button
        ref={anchorRef}
        aria-controls={open ? 'menu-list-grow' : undefined}
        aria-haspopup='true'
        onClick={handleToggle}
      >
        <Badge
          anchorOrigin={{
            vertical: 'top',
            horizontal: 'right'
          }}
          badgeContent={teks.length}
          color='primary'
        >
          <MenuBookIcon style={{fontSize: 30}} />
        </Badge>
      </Button>
      <Popper transition disablePortal open={open} anchorEl={anchorRef.current} role={undefined}>
        {({TransitionProps, placement}) => (
          <Grow
            {...TransitionProps}
            style={{transformOrigin: placement === 'bottom' ? 'center top' : 'center bottom'}}
          >
            <Paper>
              <ClickAwayListener onClickAway={handleClose}>
                <MenuList autoFocusItem={open} id='menu-list-grow' onKeyDown={handleListKeyDown}>
                  {teks.map(t => <MenuItem key={t._id} onClick={() => handleClick(t.slug)}>{t.tit}</MenuItem>)}
                </MenuList>
              </ClickAwayListener>
            </Paper>
          </Grow>
        )}
      </Popper>
    </div>
  )
}

MizikBadjMeni.propTypes = {
  teks: PropTypes.array.isRequired
}
