import { IconButton } from '@mui/material';
import { IconGripVertical } from '@tabler/icons-react';

import { useItemContext } from '../../context';
import { type DragHandleProps } from '../../types';

const DragHandle = ({ children, sx = {} }: DragHandleProps) => {
  const { listeners, attributes, setActivatorNodeRef, isDraggable } =
    useItemContext();

  if (!isDraggable) {
    return null;
  }

  // If no drag functionality (e.g., in overlay), just render the visual
  if (!listeners || !attributes || !setActivatorNodeRef) {
    return (
      <IconButton sx={{ cursor: 'grab', ...sx }}>
        {children || <IconGripVertical />}
      </IconButton>
    );
  }

  return (
    <IconButton
      sx={{ cursor: 'grab', ...sx }}
      ref={setActivatorNodeRef}
      {...listeners}
      {...attributes}
    >
      {children || <IconGripVertical />}
    </IconButton>
  );
};

DragHandle.displayName = 'SortableList.DragHandle';

export default DragHandle;
