import { type FC, useCallback } from 'react';

import SortableList from '@material-hu/components/composed-components/SortableList';
import { type ItemComponentProps } from '@material-hu/components/composed-components/SortableList/types';

import { type ViewListItem } from 'src/pages/dashboard/serviceManagement/types';

import PrivateViewListItem from './ViewListItem';

type Props = {
  views: ViewListItem[];
  onRename: (view: ViewListItem) => void;
  onDelete: (view: ViewListItem) => void;
  selectedViewId?: string;
  viewsWithBubble?: Set<string>;
  onSelect: (id: string) => void;
  onReorderView: (id: string, destinationIdx: number) => void;
};

const ViewList: FC<Props> = ({
  views,
  onRename,
  onDelete,
  selectedViewId,
  viewsWithBubble,
  onSelect,
  onReorderView,
}) => {
  const renderItem = useCallback(
    ({ item }: ItemComponentProps<ViewListItem>) => (
      <PrivateViewListItem
        view={item}
        onRename={onRename}
        onDelete={onDelete}
        selected={item.id === selectedViewId}
        hasBubble={viewsWithBubble?.has(item.id)}
        onSelect={onSelect}
      />
    ),
    [onRename, onDelete, selectedViewId, viewsWithBubble, onSelect],
  );

  return (
    <SortableList
      items={views}
      ItemComponent={renderItem}
      onSort={(_, oldIndex, newIndex) => {
        const viewToMove = views[oldIndex];

        if (viewToMove) {
          onReorderView(viewToMove.id, newIndex);
        }
      }}
      sx={{
        width: 1,
        height: '100%',
        gap: 1,
        overflowX: 'hidden',
        overflowY: 'auto',
      }}
    />
  );
};

export default ViewList;
