import { useMemo, useRef } from 'react';

import { SidebarEmpty } from '@composed-components/LibrariesSidebar/components/empty/SidebarEmpty';
import { SortableRootRow } from '@composed-components/LibrariesSidebar/components/list/root/SortableRootRow';
import { SortableRows } from '@composed-components/LibrariesSidebar/components/list/SortableRows';
import { SidebarLoading } from '@composed-components/LibrariesSidebar/components/loading/SidebarLoading';
import { ROOT_ROW_HEIGHT } from '@composed-components/LibrariesSidebar/constants';
import { useSidebarColors } from '@composed-components/LibrariesSidebar/hooks/useGetSidebarColors';
import { useSortableList } from '@composed-components/LibrariesSidebar/hooks/useSortableList';
import {
  getRootListSx,
  getRootVirtualRowStyle,
} from '@composed-components/LibrariesSidebar/styles';
import { type SidebarRootListProps } from '@composed-components/LibrariesSidebar/types';
import useVirtualizer from '@hooks/useVirtualizer';
import { Stack, useTheme } from '@mui/material';

export const SidebarRootList = ({ loading }: SidebarRootListProps) => {
  const { palette } = useTheme();
  const colors = useSidebarColors();
  const { isSortMode, listItems, handleDragEnd } = useSortableList();

  const scrollElementRef = useRef<HTMLDivElement>(null);

  const { virtualRows, rowVirtualizer } = useVirtualizer({
    scrollElementRef,
    registers: listItems,
    virtualizerOptions: {
      count: listItems.length,
      estimateSize: () => ROOT_ROW_HEIGHT,
      getScrollElement: () => scrollElementRef.current,
      overscan: 8,
    },
  });

  const listSx = useMemo(() => getRootListSx(colors), [colors]);

  if (loading) return <SidebarLoading />;

  if (!listItems.length) {
    return (
      <SidebarEmpty
        sx={{ backgroundColor: palette.new.background.elements.default }}
      />
    );
  }

  if (isSortMode) {
    return (
      <SortableRows
        items={listItems}
        onDragEnd={handleDragEnd}
        renderRow={item => <SortableRootRow item={item} />}
        sx={listSx}
      />
    );
  }

  return (
    <Stack
      ref={scrollElementRef}
      sx={listSx}
    >
      <Stack
        style={{
          height: `${rowVirtualizer.getTotalSize()}px`,
          width: '100%',
          position: 'relative',
        }}
      >
        {virtualRows.map(virtualRow => {
          const item = listItems[virtualRow.index];
          if (!item) return null;

          return (
            <div
              key={item.id}
              style={getRootVirtualRowStyle(virtualRow.start)}
            >
              <SortableRootRow item={item} />
            </div>
          );
        })}
      </Stack>
    </Stack>
  );
};
