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

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

import {styled} from '@mui/material/styles'
import MenuBookIcon from '@mui/icons-material/MenuBook'

const PREFIX = 'mizik-badj-meni'

const classes = {
  root: `${PREFIX}-root`,
  paper: `${PREFIX}-paper`
}

const Root = styled('div')((
  {
    theme
  }
) => ({
  [`&.${classes.root}`]: {
    display: 'flex'
  },

  [`& .${classes.paper}`]: {
    marginRight: theme.spacing(2)
  }
}))

const sortTeks = paroles => paroles.sort((a, b) => b.id - a.id)

export default function MizikBadjMeni({paroles}) {
  const [open, setOpen] = useState(false)
  const anchorRef = useRef(null)
  const router = useRouter()
  const sortedTeks = sortTeks(paroles)

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

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

    setOpen(false)
  }

  const handleClick = slug => {
    router.push(`/paroles/${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 (
    <Root 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={paroles.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()}>
                  {sortedTeks.map(({id, slug, titre}) => <MenuItem key={id} onClick={() => handleClick(slug)}>{titre}</MenuItem>)}
                </MenuList>
              </ClickAwayListener>
            </Paper>
          </Grow>
        )}
      </Popper>
    </Root>
  )
}

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