import { ReactNode } from 'react';
import type { DraggableAttributes } from '@dnd-kit/core';
import { SyntheticListenerMap } from '@dnd-kit/core/dist/hooks/utilities';
import { useSortable } from '@dnd-kit/sortable';
import type { Transform } from '@dnd-kit/utilities';
import { CSS } from '@dnd-kit/utilities';

type RenderProps = {
  dndAttributes: DraggableAttributes;
  dndListeners?: SyntheticListenerMap;
  dndSetNodeRef: (node: HTMLElement | null) => void;
  dndTransform: Transform | null;
  dndTransition?: string;
  dndStyle: {
    transform?: string;
    transition?: string;
  };
  dndIsDragging: boolean;
};

type Props = {
  value: string | number;
  children: (props: RenderProps) => ReactNode;
  isDragDisabled?: boolean;
};

function SortableItem({ value, children, isDragDisabled = false }: Props) {
  const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
    id: value,
    disabled: isDragDisabled,
  });

  const style = {
    transform: CSS.Translate.toString(transform),
    transition: transition || undefined,
  };

  return children({
    dndAttributes: attributes,
    dndListeners: listeners,
    dndSetNodeRef: setNodeRef,
    dndTransform: transform,
    dndTransition: transition,
    dndStyle: style,
    dndIsDragging: isDragging,
  });
}

export default SortableItem;
