import {useSortable} from '@dnd-kit/sortable';
import {
  CSSProperties,
  FC,
  HTMLAttributes,
  ReactElement,
  cloneElement,
} from 'react';
import {ShowContextMenuParams} from 'react-contexify';

type MakeOptional<Type, Key extends keyof Type> = Omit<Type, Key> &
  Partial<Pick<Type, Key>>;

type Props = {
  id: string;
  showContext: (
    params: MakeOptional<ShowContextMenuParams<unknown>, 'id'>,
  ) => void;
  children: ReactElement;
} & HTMLAttributes<HTMLDivElement>;

const DraggableItem: FC<Props> = function ({
  id,
  children,
  showContext,
  ...props
}) {
  const {setNodeRef, attributes, listeners, transition, transform} =
    useSortable({id});

  const style: CSSProperties = {
    ...props.style,
    transition,
    transform: `translate3d(${transform?.x ?? 0}px, ${transform?.y ?? 0}px, 0)`,
  };

  return cloneElement(children, {
    onContextMenu(e: MouseEvent) {
      id === '-1'
        ? e.preventDefault()
        : showContext({event: e, props: {key: id}});
    },
    style,
    ref: setNodeRef,
    ...attributes,
    ...listeners,
  });
};

export default DraggableItem;
