import { memo, useContext } from 'react';

import { useSidebarContext } from '@composed-components/LibrariesSidebar/context';
import { useSidebarColors } from '@composed-components/LibrariesSidebar/hooks/useGetSidebarColors';
import {
  AVATAR_STYLES,
  getRootRowSx,
} from '@composed-components/LibrariesSidebar/styles';
import { type SortableRootRowProps } from '@composed-components/LibrariesSidebar/types';
import { getAvatarConfig } from '@composed-components/LibrariesSidebar/utils';
import { ItemContext } from '@composed-components/SortableListComposition';
import ListItem from '@design-system/List/components/ListItem';
import Stack from '@mui/material/Stack';
import { IconChevronRight } from '@tabler/icons-react';

import { DragIcon } from '../../DragIcon';

const SortableRootRowComponent = ({ item }: SortableRootRowProps) => {
  const colors = useSidebarColors();
  const { onItemClick, isSortMode } = useSidebarContext();
  const isDragging = useContext(ItemContext)?.isDragging ?? false;

  const handleClick = () => {
    if (!item || isSortMode) return;
    onItemClick?.(item);
  };

  return (
    <Stack sx={getRootRowSx(colors, isSortMode, isDragging)}>
      <DragIcon />
      <ListItem
        key={item.id}
        component="div"
        onClick={isSortMode ? undefined : handleClick}
        text={{ title: item.title }}
        avatar={getAvatarConfig(item)}
        action={{ Icon: IconChevronRight, onClick: handleClick }}
        sx={{ width: '100%' }}
        slotProps={{
          avatar: { sx: AVATAR_STYLES },
          container: { sx: { py: 1.5 } },
          title: {
            slotProps: {
              title: {
                sx: { color: colors.TITLE_COLOR },
                overflow: 'tooltip',
                withEllipsis: true,
              },
            },
          },
        }}
      />
    </Stack>
  );
};

export const SortableRootRow = memo(SortableRootRowComponent);
