import { memo, useContext, useState } from 'react';

import { SidebarAddItemButton } from '@composed-components/LibrariesSidebar/components/create/SidebarAddItemButton';
import { SidebarChildrenList } from '@composed-components/LibrariesSidebar/components/list/children/SidebarChildrenList';
import { useSidebarContext } from '@composed-components/LibrariesSidebar/context';
import { useSidebarColors } from '@composed-components/LibrariesSidebar/hooks/useGetSidebarColors';
import {
  getChildRowContainerSx,
  getChildRowDetailsSx,
  getChildRowSummarySx,
  getChildRowTitleSx,
  getCollapseIconSx,
} from '@composed-components/LibrariesSidebar/styles';
import { type SidebarChildRowProps } from '@composed-components/LibrariesSidebar/types';
import { getAvatarConfig } from '@composed-components/LibrariesSidebar/utils';
import { ItemContext } from '@composed-components/SortableListComposition';
import { TextOverflowTip } from '@composed-components/TextOverflowTip';
import Avatar from '@design-system/Avatar';
import { Box, Collapse, IconButton, Stack } from '@mui/material';
import { IconChevronDown } from '@tabler/icons-react';

const SidebarChildRowComponent = ({
  item,
  depth,
  onAdd,
}: SidebarChildRowProps) => {
  const colors = useSidebarColors();
  const isDragging = useContext(ItemContext)?.isDragging ?? false;
  const {
    onItemClick,
    onAddMouseEnter,
    isSortMode,
    expandedIds,
    setRowExpanded,
  } = useSidebarContext();
  const [expanded, setExpanded] = useState(() => expandedIds.has(item.id));
  const [hovering, setHovering] = useState(false);

  const isNested = depth > 0;
  const showDragIcon = hovering && isSortMode;
  // Only leaves that can't grow hide the toggle; children stay reachable at limit.
  const hideExpand =
    !item.hasChildren && Boolean(item.hasReachedLimit || item.hideCreateButton);
  const showCreateButton = !item.hasReachedLimit && !item.hideCreateButton;

  const handleSummaryClick = () => {
    if (isSortMode) return;
    onItemClick?.(item);
  };

  const handleToggle = (e: React.MouseEvent) => {
    e.stopPropagation();
    setExpanded(prev => {
      const next = !prev;
      setRowExpanded(item.id, next);
      return next;
    });
  };

  return (
    <Stack
      sx={getChildRowContainerSx(colors, isNested, isSortMode, isDragging)}
    >
      <Stack
        className="accordion-summary"
        onClick={handleSummaryClick}
        onMouseEnter={isSortMode ? () => setHovering(true) : undefined}
        onMouseLeave={isSortMode ? () => setHovering(false) : undefined}
        sx={getChildRowSummarySx(colors, {
          depth,
          isNested,
          expanded,
          isSortMode,
          isDragging,
          showDragIcon,
        })}
      >
        <Avatar {...getAvatarConfig(item, showDragIcon)} />
        <TextOverflowTip
          primary={item.title}
          slotProps={{
            typography: {
              variant: 'globalS',
              fontWeight: 'semiBold',
              sx: getChildRowTitleSx(colors),
            },
          }}
        />
        {!hideExpand && (
          <IconButton
            className="accordion-collapse-icon"
            size="small"
            onClick={handleToggle}
            sx={getCollapseIconSx(colors, expanded)}
          >
            <IconChevronDown />
          </IconButton>
        )}
      </Stack>
      {!hideExpand && (
        <Collapse
          in={expanded}
          mountOnEnter
          unmountOnExit
        >
          <Box
            className="accordion-details-custom-detail"
            sx={getChildRowDetailsSx(colors, isNested)}
          >
            <SidebarChildrenList
              depth={depth + 1}
              parentId={item.id}
              onAdd={onAdd}
            />
            {showCreateButton && (
              <SidebarAddItemButton
                onAddMouseEnter={() => onAddMouseEnter?.(item.id)}
                onAdd={() => onAdd?.(item.id)}
                depth={depth}
                hasChildren={item.hasChildren}
              />
            )}
          </Box>
        </Collapse>
      )}
    </Stack>
  );
};

export const SidebarChildRow = memo(SidebarChildRowComponent);
