import {
  Box,
  Collapse,
  List,
  ListItemIcon,
  ListItemText,
  styled,
} from '@mui/material'
import { Store } from 'pullstate'
import { ReactNode, memo } from 'react'
import { Link, useMatch, useResolvedPath } from 'react-router-dom'
import { PermissionsStore, UserStore } from '../../shared-state'
import {
  ListItemButton,
  StyledChevronIcon,
  StyledListItemButton,
} from '../ListItemButton'

const accessIfNoKey = process.env.NODE_ENV === 'development' ? true : false

const checkHasAccess = (
  checkForMasterSlave,
  permissionKey,
  institutionType,
  permissions,
  checkIsMasterInstitution,
  masterInstitutionUniqueId,
  isMasterInstitution,
  user,
) => {
  if (checkForMasterSlave) {
    if (institutionType == 'MASTER_CHILD') {
      if (checkIsMasterInstitution) {
        return (
          permissions[permissionKey] &&
          user.institutionIds.includes(masterInstitutionUniqueId) &&
          isMasterInstitution
        )
      }
      return permissionKey ? permissions[permissionKey] : true
    }
  }
  return permissionKey ? permissions[permissionKey] : true
}

const sideNavStore = new Store({
  activeKey: '',
})

const StyledLink = styled(Link)({
  textDecoration: 'none',
})

const SideNav = ({
  menuItems,
  header,
}: {
  menuItems: any[]
  header?: ReactNode
}) => {
  return (
    <Box
      sx={{
        background: (theme) => theme.palette.secondary.main,
      }}
    >
      {header ? header : null}
      <Box sx={{ ':first-child': { marginTop: '25px' } }}>
        {menuItems.map((item, index) => (
          <RenderMenuItem key={index} menuItem={item} />
        ))}
      </Box>
    </Box>
  )
}

export default memo(SideNav)

const RenderMenuItem = ({ menuItem }) => {
  const {
    path,
    children,
    title,
    icon,
    permissionKey,
    checkForMasterSlave,
    checkIsMasterInstitution,
  } = menuItem

  let resolved = useResolvedPath(path)
  let match = useMatch({ path: resolved.pathname, end: false })

  const {
    permissions,
    institutionType,
    masterInstitutionUniqueId,
    isMasterInstitution,
  } = PermissionsStore.useState((s) => s)
  const { user } = UserStore.useState((s) => s)

  const hasAccess = checkHasAccess(
    checkForMasterSlave,
    permissionKey,
    institutionType,
    permissions,
    checkIsMasterInstitution,
    masterInstitutionUniqueId,
    isMasterInstitution,
    user,
  )

  if (children?.length)
    return (
      <Box sx={{ position: 'relative' }}>
        <DropDownMenu
          icon={icon}
          menuItems={children}
          path={path}
          title={title}
        />
      </Box>
    )

  return (
    <>
      {hasAccess ? (
        <>
          <StyledLink to={path}>
            <ListItemButton
              hasChildren={false}
              label={title}
              isActive={!!match}
              icon={icon}
            />
          </StyledLink>
          {menuItem?.sectionEnd && (
            <Box
              sx={{
                backgroundColor: '#1D1D1D',
                height: '5px',
              }}
            ></Box>
          )}
        </>
      ) : null}
    </>
  )
}

const DropDownMenu = ({ path, title, icon, menuItems }) => {
  const { activeKey } = sideNavStore.useState((s) => s)
  const {
    permissions,
    institutionType,
    masterInstitutionUniqueId,
    isMasterInstitution,
  } = PermissionsStore.useState((s) => s)
  const { user } = UserStore.useState((s) => s)

  const validateDropdownAccess = () => {
    if (process.env.NODE_ENV === 'development' && !permissions) return true

    return menuItems?.some((item) =>
      item?.permissionKey
        ? checkHasAccess(
            item?.checkForMasterSlave,
            item?.permissionKey,
            institutionType,
            permissions,
            item?.checkIsMasterInstitution,
            masterInstitutionUniqueId,
            isMasterInstitution,
            user,
          )
        : accessIfNoKey,
    )
  }

  if (!validateDropdownAccess()) return null
  return (
    <Box sx={{ position: 'relative' }}>
      <MenuDropDownButton
        isActive={activeKey === path}
        onClick={() => {
          sideNavStore.update((s) => {
            s.activeKey = activeKey === path ? '' : path
          })
        }}
        label={title}
        icon={icon}
      />
      <Collapse timeout={200} in={activeKey === path}>
        <List>
          {menuItems?.map((child) => (
            <RenderMenuItem
              key={child.path}
              menuItem={{
                ...child,
                path: path + child.path,
              }}
            />
          ))}
        </List>
      </Collapse>
      {menuItems?.sectionEnd && (
        <Box
          sx={{
            backgroundColor: '#1D1D1D',
            height: '5px',
          }}
        ></Box>
      )}
    </Box>
  )
}

const MenuDropDownButton = ({ icon: Icon, label, onClick, isActive }) => {
  return (
    <>
      <StyledListItemButton
        dropDown={true}
        onClick={onClick}
        isActive={isActive}
      >
        {Icon ? (
          <ListItemIcon>{<Icon />}</ListItemIcon>
        ) : (
          <Box minWidth={16}></Box>
        )}
        <ListItemText primary={label} />
        <StyledChevronIcon open={isActive} />
      </StyledListItemButton>
    </>
  )
}
