import { useState } from 'react'
import { Box, Button, Menu, Grid } from '@mui/material'
import { ArrowDropDownRounded } from '@mui/icons-material'
import { useLocation, useNavigate } from 'react-router-dom'
import { useRoutesMap } from '@/configs/routes'
import ProductMenuLink from './ProductMenuLink'
import type { Nullable } from '@/utils/types'
import type { PathRenderProps, To } from '../layout'

const ProductDrawser: React.FC = () => {
  const [anchorEl, setAnchorEl] = useState<Nullable<Element>>(null)
  const opened = anchorEl === null ? false : true
  const handleClick = (event: any) => {
    setAnchorEl(event.currentTarget)
  }
  const handleClose = () => {
    setAnchorEl(null)
  }
  const navigate = useNavigate()
  const location = useLocation()
  const { pathname } = location
  const routesMap = useRoutesMap()
  const pathMeta = routesMap.get(pathname)
  const renderPath: PathRenderProps[] = []
  routesMap.forEach((value, key) => {
    const { meta } = value
    if (meta && meta.type === 'LINK') {
      renderPath.push({
        path: key || '/',
        metaName: meta.name,
        metaType: meta.type,
        metaIcon: meta.icon,
        metaDesc: meta.desc || meta.name || '',
      })
    }
  })

  const jumpto = (path: To) => {
    handleClose()
    navigate(path)
  }

  return (
    <Box>
      <Button
        id="ya-product-controller"
        aria-controls="drawer-open-button"
        aria-haspopup="true"
        aria-expanded={opened ? 'true' : undefined}
        onClick={handleClick}
        endIcon={<ArrowDropDownRounded fontSize="small" sx={{ ml: -0.5 }} />}
        sx={(theme) => ({
          py: 0.1,
          minWidth: 0,
          fontSize: '.5rem',
          color:
            theme.palette.mode === 'dark' ? theme.palette.primary[300] : theme.palette.primary[600],
          '& svg': {
            ml: -1,
            width: 18,
            height: 18,
          },
        })}
      >
        <strong style={{ textTransform: 'none' }}>{pathMeta?.meta?.name}</strong>
      </Button>
      <Menu
        id="mui-product-menu"
        anchorEl={anchorEl}
        open={opened}
        onClose={handleClose}
        MenuListProps={{
          'aria-labelledby': 'ya-product-controller',
        }}
        PaperProps={{
          sx: {
            width: 560,
            padding: '.4rem',
          },
        }}
      >
        <Grid container columnSpacing={1}>
          {renderPath.map((item) => (
            <Grid item xs={4} key={item.path}>
              <ProductMenuLink
                icon={item.metaIcon}
                path={item.path}
                name={item.metaName}
                description={item.metaDesc}
                onClick={jumpto}
                isActive={pathname === item.path}
              />
            </Grid>
          ))}
        </Grid>
      </Menu>
    </Box>
  )
}

export default ProductDrawser
