import {useRef, useState} from 'react'
import PropTypes from 'prop-types'
import {useRouter} from 'next/router'
import {Button, ListItemIcon, ListItemText, Menu, MenuItem, withStyles} from '@material-ui/core'
import PublicIcon from '@material-ui/icons/Public'

const StyledMenu = withStyles({
  paper: {
    border: '1px solid #d3d4d5'
  }
})(props => (
  <Menu
    elevation={0}
    getContentAnchorEl={null}
    anchorOrigin={{
      vertical: 'bottom',
      horizontal: 'center'
    }}
    transformOrigin={{
      vertical: 'top',
      horizontal: 'center'
    }}
    {...props}
  />
))

const StyledMenuItem = withStyles(theme => ({
  root: {
    '&:hover': {
      backgroundColor: theme.palette.primary.main,
      '& .MuiListItemIcon-root, & .MuiListItemText-primary': {
        color: theme.palette.common.white
      }
    }
  }
}))(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 => {
    setAnchorElement(null)
    if (typeof rezo === 'string') {
      const url = `https://${rezo}.${siteDomain}`
      router.push(url)
    }
  }

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

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