import {useRef, useState} from 'react'
import {styled} from '@mui/material/styles'
import PropTypes from 'prop-types'
import {useRouter} from 'next/navigation'
import {Button, ListItemIcon, ListItemText, Menu, MenuItem} from '@mui/material'
import PublicIcon from '@mui/icons-material/Public'

const PREFIX = 'rezo-menu'

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

const Root = styled('div')((
  {
    theme
  }
) => ({
  [`& .${classes.paper}`]: {
    border: '1px solid #d3d4d5'
  },

  [`& .${classes.root}`]: {
    '&:hover': {
      backgroundColor: theme.palette.primary.main,
      '& .MuiListItemIcon-root, & .MuiListItemText-primary': {
        color: theme.palette.common.white
      }
    }
  }
}))

function StyledMenu(props) {
  return (
    <Menu
      elevation={0}
      anchorOrigin={{
        vertical: 'bottom',
        horizontal: 'center'
      }}
      transformOrigin={{
        vertical: 'top',
        horizontal: 'center'
      }}
      {...props}
    />
  )
}

const StyledMenuItem = MenuItem

const siteDomain = process.env.NEXT_PUBLIC_PROD_DOMAIN || 'localhost'

export default function RezoMenu({data}) {
  const router = useRouter()
  const [anchorElement, setAnchorElement] = useState(null)
  const anchorRef = useRef(null)

  const handleClick = event => {
    setAnchorElement(event.currentTarget)
  }

  const handleClose = (rezo, link) => {
    setAnchorElement(null)
    if (typeof rezo === 'string' && !link) {
      const url = `https://${rezo}.${siteDomain}`
      router.push(url)
    } else if (typeof rezo === 'string' && link) {
      window.open(link, '_blank')
    }
  }

  return (
    (
      <Root>
        <Button
          ref={anchorRef}
          startIcon={<PublicIcon />}
          size='small'
          aria-controls='customized-menu'
          aria-haspopup='true'
          variant='contained'
          color='primary'
          onClick={handleClick}
        >
          Rézo
        </Button>
        <StyledMenu
          keepMounted
          id='customized-menu'
          anchorEl={anchorElement}
          open={Boolean(anchorElement)}
          classes={{
            paper: classes.paper
          }}
          onClose={handleClose}
        >
          {data.map(({id, tit, icon, link}) => (
            <StyledMenuItem
              key={id}
              classes={{
                root: classes.root
              }}
              onClick={() => handleClose(id, link)}
            >
              <ListItemIcon>
                {icon}
              </ListItemIcon>
              <ListItemText primary={tit} />
            </StyledMenuItem>
          ))}
        </StyledMenu>
      </Root>
    )
  )
}

RezoMenu.propTypes = {
  data: PropTypes.array.isRequired
}
