import {
  DialogProps,
  DrawerProps,
  ListItemIcon,
  ListItemText,
  styled,
} from '@mui/material'
import { ReactNode } from 'react'
import { Link } from 'react-router-dom'
import { DrawerButtonProps } from '../ModalButtons/DrawerButton'
import { StyledMenuItem } from './styles'
import { ValidateAccess } from '../../permissions'
import { Permission } from '../../shared-state'

const StyledLink = styled(Link)(({ theme }) => ({
  display: 'block',
  textTransform: 'none',
  textDecoration: 'none',
}))

export type MenuItemType = 'normal' | 'dialog' | 'drawer' | 'link'

export type MenuItemButtonProps = {
  icon?: ReactNode
  label: ReactNode
  onClick: () => void
  link?: {
    to: string
    target?: '_self' | '_blank'
  }
}

const MenuItemButton = ({
  icon,
  label,
  onClick,
  ...props
}: MenuItemButtonProps) => {
  return (
    <StyledMenuItem
      sx={{ minWidth: '180px', width: '100%' }}
      onClick={onClick}
      {...props}
    >
      {icon && <ListItemIcon>{icon}</ListItemIcon>}
      <ListItemText>{label}</ListItemText>
    </StyledMenuItem>
  )
}

export type IMenuItemProps = Omit<MenuItemButtonProps, 'onClick'> & {
  content?: DrawerButtonProps['content']
  contentTitle?: ReactNode
  actionType?: MenuItemType
  onClick?: () => void
  dialogProps?: Omit<DialogProps, 'open'>
  drawerProps?: Omit<DrawerProps, 'open'>
  permissionKey?: Permission
}

export interface IRenderMenuItemProps extends IMenuItemProps {
  handleClose: () => void
  modalState: any
  onModalOpen: (props: any) => void
}

export const RenderMenuItem = ({
  onClick,
  actionType = 'normal',
  handleClose,
  modalState,
  onModalOpen,
  link,
  drawerProps,
  dialogProps,
  permissionKey,
  ...props
}: IRenderMenuItemProps) => {
  const renderMenuItem: Record<MenuItemType, ReactNode> = {
    normal: (
      <MenuItemButton
        {...props}
        onClick={() => {
          onClick()
          handleClose()
        }}
      />
    ),
    dialog: (
      <MenuItemButton
        {...props}
        onClick={() => {
          onModalOpen(dialogProps)
          handleClose()
        }}
      />
    ),
    drawer: (
      <MenuItemButton
        {...props}
        onClick={() => {
          onModalOpen(drawerProps)
          handleClose()
        }}
      />
    ),
    link: (
      <StyledLink to={link?.to ?? ''} target={link?.target ?? '_blank'}>
        <MenuItemButton {...props} onClick={() => {}} />
      </StyledLink>
    ),
  }

  if (permissionKey)
    return (
      <ValidateAccess accessKey={permissionKey}>
        {renderMenuItem[actionType]}
      </ValidateAccess>
    )

  return <>{renderMenuItem[actionType]}</>
}
