import { type FC, useEffect, useState } from 'react';
import { NavLink as RouterLink } from 'react-router-dom';

import Badge from '@design-system/Badge';
import Tooltip from '@design-system/Tooltip';
import { Button, Collapse, Stack, type SxProps, useTheme } from '@mui/material';
import ListItem from '@mui/material/ListItem';
import { IconChevronDown, IconChevronRight } from '@tabler/icons-react';

import { type NavItemProps } from '../../types';
import NavButtonContent from '../NavButtonContent';

import { BUTTON_HEIGHT } from './constants';

const NavItem: FC<NavItemProps> = props => {
  const {
    active,
    children,
    depth,
    icon,
    info,
    open: openProp,
    path = '',
    title,
    isCollapsed,
    hasChildrenButCollapsed = false,
    openMenu = () => {},
    isLastChild = false,
    skipLinkBehavior = false,
    onClick,
    fallbackPath,
  } = props;
  const [open, setOpen] = useState<boolean>(openProp ?? false);

  const theme = useTheme();

  const commonStyles = {
    height: BUTTON_HEIGHT,
    color: theme.palette.new.text.neutral.lighter,
    '& svg': {
      stroke: `${theme.palette.new.text.neutral.lighter} !important`,
    },
    ...(active && {
      color: theme.palette.new.text.neutral.default,
      '& svg': {
        stroke: 'currentColor',
      },
    }),
  };

  const commonStylesNotCollapsed = {
    ...commonStyles,
    '&:hover': {
      backgroundColor: theme.palette.new.action.background.neutral.hover,
      ...(active && {
        '& svg': {
          stroke: `${theme.palette.new.text.neutral.default} !important`,
        },
      }),
    },
    gap: 1,
    pb: theme.spacing(1.5),
    pt: theme.spacing(1.5),
    textTransform: 'none',
    width: '100%',
  };

  const isDarkMode = theme.palette.mode === 'dark';
  const activeBackgroundColorDepth = isDarkMode
    ? theme.palette.new.action.background.neutral.focusDarker
    : theme.palette.new.background.elements.brand;

  const backgroundColorDepth = theme.palette.new.background.layout.default;

  const handleToggle = (): void => {
    setOpen(prevOpen => !prevOpen);
  };

  const handleClick = () => {
    onClick?.();
    if (isCollapsed && hasChildrenButCollapsed) {
      openMenu();
      setOpen(true);
    }
  };

  useEffect(() => {
    if (!isCollapsed && hasChildrenButCollapsed) {
      setOpen(false);
    }
  }, [isCollapsed]);

  // Branch
  if (children) {
    return (
      <ListItem
        disableGutters
        sx={{
          display: 'block',
          py: 0,
        }}
      >
        <Collapse
          sx={{
            borderBottomLeftRadius: theme.shape.borderBottomLeftRadiusL,
            borderBottomRightRadius: theme.shape.borderBottomRightRadiusL,
          }}
          in={open}
          collapsedSize={BUTTON_HEIGHT}
        >
          <Button
            onClick={handleToggle}
            sx={{
              ...(commonStylesNotCollapsed as SxProps),
              borderBottomLeftRadius: 0,
              borderBottomRightRadius: 0,
              borderTopLeftRadius: theme.shape.borderTopLeftRadiusL,
              borderTopRightRadius: theme.shape.borderTopRightRadiusL,
              pl: theme.spacing(1),
              pr: theme.spacing(1),
              textAlign: 'left',
              ...(open && {
                backgroundColor: backgroundColorDepth,
              }),
              ...(active && {
                backgroundColor: activeBackgroundColorDepth,
              }),
            }}
            variant="tertiary"
          >
            <NavButtonContent
              active={active}
              icon={icon}
              title={title}
              info={info}
            >
              <>
                {!open ? (
                  <IconChevronRight fontSize="small" />
                ) : (
                  <IconChevronDown fontSize="small" />
                )}
              </>
            </NavButtonContent>
          </Button>
          {children}
        </Collapse>
      </ListItem>
    );
  }

  const isRouterComponent = path && !skipLinkBehavior;

  const isDepth = depth > 0;

  const buttonProps = isRouterComponent
    ? {
        component: RouterLink,
        to: hasChildrenButCollapsed ? fallbackPath : path,
        onClick: handleClick,
      }
    : {
        component: 'button',
        onClick: handleClick,
      };

  // Leaf
  return (
    <ListItem
      disableGutters
      sx={{
        display: 'flex',
        py: 0,
      }}
    >
      {isCollapsed && (
        <Tooltip
          description={title}
          direction="right"
        >
          <Button
            {...buttonProps}
            sx={{
              ...commonStyles,
              minWidth: 40,
              py: theme.spacing(1.5),
              px: theme.spacing(1),
              borderRadius: theme.shape.borderRadiusL,
              ...(active && {
                backgroundColor: activeBackgroundColorDepth,
              }),
            }}
          >
            <Badge
              variant="dot"
              color="primary"
              invisible={!info?.notificationCount}
            >
              <Stack
                sx={{
                  ...commonStyles,
                  width: 24,
                  height: 24,
                }}
              >
                {icon}
              </Stack>
            </Badge>
          </Button>
        </Tooltip>
      )}
      {!isCollapsed && (
        <Button
          {...buttonProps}
          sx={{
            ...(commonStylesNotCollapsed as SxProps),
            backgroundColor: isDepth ? backgroundColorDepth : undefined,
            borderBottomLeftRadius:
              !isDepth || isLastChild ? theme.shape.borderBottomLeftRadiusL : 0,
            borderBottomRightRadius:
              !isDepth || isLastChild
                ? theme.shape.borderBottomRightRadiusL
                : 0,
            borderTopLeftRadius: isDepth ? 0 : theme.shape.borderTopLeftRadiusL,
            borderTopRightRadius: isDepth
              ? 0
              : theme.shape.borderTopRightRadiusL,
            pl: isDepth ? theme.spacing(5) : theme.spacing(1),
            pr: isDepth ? theme.spacing(2) : theme.spacing(1),
            ...(active && {
              backgroundColor: activeBackgroundColorDepth,
            }),
            textAlign: 'left',
          }}
          variant="tertiary"
        >
          <NavButtonContent
            active={active}
            icon={icon}
            title={title}
            info={info}
          />
        </Button>
      )}
    </ListItem>
  );
};

export type { NavItemProps };

export default NavItem;
