import React from "react";
import { __ } from "@wordpress/i18n";
import { defaultAnimateLayoutChanges, useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";

export const ruleSortingTransition = {
  duration: 220,
  easing: "cubic-bezier(0.22, 1, 0.36, 1)",
};

const SortableRule = ({ id, className, reducedMotion, children }) => {
  const {
    attributes,
    listeners,
    setNodeRef,
    setActivatorNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({
    id,
    attributes: { roleDescription: __("sortable rule", "arraysubs") },
    transition: reducedMotion ? null : ruleSortingTransition,
    animateLayoutChanges: (args) => {
      if (reducedMotion) return false;
      return args.isSorting || args.wasDragging
        ? defaultAnimateLayoutChanges(args)
        : true;
    },
  });

  return (
    <div
      ref={setNodeRef}
      data-rule-id={id}
      className={`${className}${
        isDragging ? " arraysubs-rule-builder__rule--dragging" : ""
      }`}
      style={{
        // Translate only: unequal card heights must never stretch the editors.
        transform: CSS.Translate.toString(transform),
        transition,
      }}
    >
      {children({ ...attributes, ...listeners, ref: setActivatorNodeRef })}
    </div>
  );
};

export default SortableRule;
