import { NavItem } from './NavItem';
import { Dot, Transitions } from '@/components/@extended';
import { useMenuConfig } from '@/components/Layout/MenuProvider';
import { useLayoutMediaState } from '@/components/Layout/Provider';
import { BorderOutlined, DownOutlined, RightOutlined, UpOutlined } from '@ant-design/icons';
import {
  Box,
  ClickAwayListener,
  Collapse,
  List,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Paper,
  Popper,
  Theme,
  Typography
} from '@mui/material';
import { styled, useTheme } from '@mui/material/styles';
import { useEffect, useMemo, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';

const PopperStyled = styled(Popper)(({ theme }: { theme: Theme }) => ({
  overflow: 'visible',
  zIndex: 1202,
  minWidth: 180,
  '&:before': {
    content: '""',
    display: 'block',
    position: 'absolute',
    top: 38,
    left: -5,
    width: 10,
    height: 10,
    backgroundColor: theme.palette.background.paper,
    transform: 'translateY(-50%) rotate(45deg)',
    zIndex: 120,
    borderLeft: `1px solid ${theme.palette.divider}`,
    borderBottom: `1px solid ${theme.palette.divider}`
  }
}));

type NavCollapseProps = {
  menu: any;
  level: number;
  parentId: string;
  setSelectedItems: (value: string) => void;
  selectedItems: string;
  setSelectedLevel: (value: number) => void;
  selectedLevel: number;
  onItemClick?: () => void;
};

function NavCollapse({
  menu,
  level,
  parentId,
  setSelectedItems,
  selectedItems,
  setSelectedLevel,
  selectedLevel,
  onItemClick
}: NavCollapseProps) {
  const theme = useTheme();
  const { activeItem } = useMenuConfig();
  const { horizontal } = useLayoutMediaState();
  const { drawerOpen } = useMenuConfig();
  const Navigation = useNavigate();

  const [open, setOpen] = useState(false);
  const [selected, setSelected] = useState(null);

  const [anchorEl, setAnchorEl] = useState(null);

  function handleClick(event: any) {
    setAnchorEl(null);
    setSelectedLevel(level);
    if (drawerOpen) {
      setOpen(!open);
      setSelected(!selected ? menu.id : null);
      setSelectedItems(!selected ? menu.id : '');
      if (menu.url) Navigation(`${menu.url}`);
    } else {
      setAnchorEl(event?.currentTarget);
    }
  }

  function handlerIconLink() {
    if (!drawerOpen) {
      if (menu.url) Navigation(`${menu.url}`);
    }
  }

  function handleHover(event: any) {
    setAnchorEl(event?.currentTarget);
  }

  function handleClose() {
    setOpen(false);
    setSelected(null);
    setAnchorEl(null);
  }

  const handleItemClick = onItemClick
    ? () => {
        handleClose();
        onItemClick();
      }
    : undefined;

  useMemo(() => {
    if (selected === selectedItems) {
      if (level === 1) {
        setOpen(true);
      }
    } else {
      if (level === selectedLevel) {
        setOpen(false);
        setSelected(null);
      }
    }
  }, [selectedItems, level, selected, selectedLevel]);

  const { pathname } = useLocation();
  const openMini = Boolean(anchorEl);

  function checkOpenForParent(child: any, id: any) {
    child.forEach((item: any) => {
      if (item.url === pathname) {
        setOpen(true);
        setSelected(id);
      }
    });
  }

  useEffect(() => {
    setOpen(false);
    setSelected(null);
    if (openMini) setAnchorEl(null);
    if (menu.children) {
      menu.children.forEach((item: any) => {
        if (item.children?.length) {
          checkOpenForParent(item.children, menu.id);
        }
        if (item.url === pathname) {
          setSelected(menu.id);
          setOpen(true);
        }
        if (pathname.includes(item.url)) {
          setSelected(menu.id);
          setOpen(true);
        }
      });
    }

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pathname, menu.children]);

  useEffect(() => {
    if (menu.url === pathname && selected !== menu.id) {
      activeItem([menu.id]);
      setSelected(menu.id);
      setAnchorEl(null);
      setOpen(true);
    }
  }, [pathname, menu, selected, activeItem]);

  const navCollapse = menu.children?.map((item: any) => {
    switch (item.type) {
      case 'collapse':
        return (
          <NavCollapse
            key={item.id}
            setSelectedItems={setSelectedItems}
            setSelectedLevel={setSelectedLevel}
            selectedLevel={selectedLevel}
            selectedItems={selectedItems}
            menu={item}
            level={level + 1}
            parentId={parentId}
            onItemClick={handleItemClick}
          />
        );
      case 'item':
        return <NavItem key={item.id} item={item} level={level + 1} onItemClick={handleItemClick} />;
      default:
        return (
          <Typography key={item.id} variant="h6" color="error" align="center">
            Fix - Collapse or Item
          </Typography>
        );
    }
  });

  const isSelected = selected === menu.id;
  const borderIcon = level === 1 ? <BorderOutlined style={{ fontSize: '1rem' }} /> : false;
  const Icon = menu.icon;
  const menuIcon = menu.icon ? <Icon style={{ fontSize: drawerOpen ? '1rem' : '1.25rem' }} /> : borderIcon;
  const textColor = theme.palette.mode === 'dark' ? 'grey.400' : 'text.primary';
  const iconSelectedColor =
    theme.palette.mode === 'dark' && drawerOpen ? theme.palette.text.primary : theme.palette.primary.main;
  const popperId = openMini ? `collapse-pop-${menu.id}` : undefined;
  const FlexBox = {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    width: '100%'
  };

  return (
    <>
      {!horizontal ? (
        <>
          <ListItemButton
            disableRipple
            selected={selected === menu.id}
            {...(!drawerOpen && { onMouseEnter: handleClick, onMouseLeave: handleClose })}
            onClick={handleClick}
            sx={{
              pl: drawerOpen ? `${level * 28}px` : 1.5,
              py: !drawerOpen && level === 1 ? 1.25 : 1,
              ...(drawerOpen && {
                '&:hover': {
                  bgcolor: theme.palette.mode === 'dark' ? 'divider' : 'primary.lighter'
                },
                '&.Mui-selected': {
                  bgcolor: 'transparent',
                  color: iconSelectedColor,
                  '&:hover': {
                    color: iconSelectedColor,
                    bgcolor: theme.palette.mode === 'dark' ? 'divider' : 'transparent'
                  }
                }
              }),
              ...(!drawerOpen && {
                '&:hover': {
                  bgcolor: 'transparent'
                },
                '&.Mui-selected': {
                  '&:hover': {
                    bgcolor: 'transparent'
                  },
                  bgcolor: 'transparent'
                }
              })
            }}
          >
            {menuIcon ? (
              <ListItemIcon
                onClick={handlerIconLink}
                sx={{
                  minWidth: 28,
                  color: selected === menu.id ? 'primary.main' : textColor,
                  ...(!drawerOpen && {
                    borderRadius: 1.5,
                    width: 36,
                    height: 36,
                    alignItems: 'center',
                    justifyContent: 'center',
                    '&:hover': {
                      bgcolor: theme.palette.mode === 'dark' ? 'secondary.light' : 'secondary.lighter'
                    }
                  }),
                  ...(!drawerOpen &&
                    selected === menu.id && {
                      bgcolor: theme.palette.mode === 'dark' ? 'primary.900' : 'primary.lighter',
                      '&:hover': {
                        bgcolor: theme.palette.mode === 'dark' ? 'primary.darker' : 'primary.lighter'
                      }
                    })
                }}
              >
                {menuIcon}
              </ListItemIcon>
            ) : null}
            {drawerOpen || (!drawerOpen && level !== 1) ? (
              <ListItemText
                primary={
                  <Typography
                    variant="h6"
                    color={selected === menu.id ? 'primary' : textColor}
                    sx={{
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                      wordBreak: 'break-word',
                      overflowWrap: 'break-word',
                      whiteSpace: 'normal',
                      display: '-webkit-box',
                      WebkitBoxOrient: 'vertical',
                      WebkitLineClamp: 2
                    }}
                  >
                    {menu.title}
                  </Typography>
                }
                secondary={
                  menu.caption ? (
                    <Typography variant="caption" color="secondary">
                      {menu.caption}
                    </Typography>
                  ) : null
                }
              />
            ) : null}
            {drawerOpen || (!drawerOpen && level !== 1) ? (
              openMini || open ? (
                <UpOutlined style={{ fontSize: '0.625rem', marginLeft: 1, color: theme.palette.primary.main }} />
              ) : (
                <DownOutlined style={{ fontSize: '0.625rem', marginLeft: 1 }} />
              )
            ) : null}

            {!drawerOpen && (
              <PopperStyled
                open={openMini}
                anchorEl={anchorEl}
                placement="right-start"
                style={{
                  zIndex: 2001
                }}
                popperOptions={{
                  modifiers: [
                    {
                      name: 'offset',
                      options: {
                        offset: [-12, 1]
                      }
                    }
                  ]
                }}
              >
                {({ TransitionProps }) => (
                  // @ts-ignore
                  <Transitions in={openMini} {...TransitionProps}>
                    <Paper
                      sx={{
                        overflow: 'hidden',
                        mt: 1.5,
                        // @ts-ignore
                        boxShadow: theme.customShadows.z1,
                        backgroundImage: 'none',
                        border: `1px solid ${theme.palette.divider}`
                      }}
                    >
                      <ClickAwayListener onClickAway={handleClose}>
                        <Box>{navCollapse}</Box>
                      </ClickAwayListener>
                    </Paper>
                  </Transitions>
                )}
              </PopperStyled>
            )}
          </ListItemButton>
          {drawerOpen ? (
            <Collapse in={open} timeout="auto" unmountOnExit>
              <List sx={{ p: 0 }}>{navCollapse}</List>
            </Collapse>
          ) : null}
        </>
      ) : (
        <>
          <ListItemButton
            id={`boundary-${popperId}`}
            disableRipple
            selected={isSelected}
            onMouseEnter={handleHover}
            onMouseLeave={handleClose}
            onClick={handleHover}
            aria-describedby={popperId}
            sx={{
              '&.Mui-selected': {
                bgcolor: 'transparent'
              }
            }}
          >
            <Box onClick={handlerIconLink} sx={FlexBox}>
              {menuIcon ? (
                <ListItemIcon
                  sx={{
                    my: 'auto',
                    minWidth: !menu.icon ? 18 : 36,
                    color: theme.palette.secondary.dark
                  }}
                >
                  {menuIcon}
                </ListItemIcon>
              ) : null}
              {!menuIcon && level !== 1 && (
                <ListItemIcon
                  sx={{
                    my: 'auto',
                    minWidth: !menu.icon ? 18 : 36,
                    bgcolor: 'transparent',
                    '&:hover': { bgcolor: 'transparent' }
                  }}
                >
                  <Dot size={4} color={isSelected ? 'primary' : 'secondary'} />
                </ListItemIcon>
              )}
              <ListItemText
                primary={
                  <Typography
                    variant="body1"
                    color="inherit"
                    sx={{
                      my: 'auto',
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                      wordBreak: 'break-word',
                      overflowWrap: 'break-word',
                      whiteSpace: 'normal',
                      display: '-webkit-box',
                      WebkitBoxOrient: 'vertical',
                      WebkitLineClamp: 2
                    }}
                  >
                    {menu.title}
                  </Typography>
                }
              />
              {openMini ? <RightOutlined style={{ marginLeft: 4 }} /> : <DownOutlined style={{ marginLeft: 4 }} />}
            </Box>

            {anchorEl ? (
              <PopperStyled
                id={popperId}
                open={openMini}
                anchorEl={anchorEl}
                placement="right-start"
                style={{
                  zIndex: 2001
                }}
                modifiers={[
                  {
                    name: 'offset',
                    options: {
                      offset: [-10, 0]
                    }
                  }
                ]}
              >
                {({ TransitionProps }) => (
                  // @ts-ignore
                  <Transitions in={openMini} {...TransitionProps}>
                    <Paper
                      sx={{
                        overflow: 'hidden',
                        mt: 1.5,
                        py: 0.5,
                        boxShadow: theme.shadows[8],
                        backgroundImage: 'none'
                      }}
                    >
                      <ClickAwayListener onClickAway={handleClose}>
                        <Box>{navCollapse}</Box>
                      </ClickAwayListener>
                    </Paper>
                  </Transitions>
                )}
              </PopperStyled>
            ) : null}
          </ListItemButton>
        </>
      )}
    </>
  );
}

export { NavCollapse };
