import { cn } from "@/lib/utils";
import { TableRow } from "@/ui/table";
import { DraggableSyntheticListeners } from "@dnd-kit/core";
import { defaultAnimateLayoutChanges, useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { CSSProperties, PropsWithChildren, createContext, useMemo } from "react";
import { QuoteItemsSortableProps } from "./QuoteItemsSortableDataTable";

interface Context {
  attributes: Record<string, any>;
  listeners: DraggableSyntheticListeners;
  ref(node: HTMLElement | null): void;
}
export const QuoteItemsSortableTableRowContext = createContext<Context>({
  attributes: {},
  listeners: undefined,
  ref() {},
});

function animateLayoutChanges(args: any) {
  if (args.isSorting || args.wasDragging) {
    return defaultAnimateLayoutChanges(args);
  }

  return true;
}

export function QuoteItemsSortableTableRow({
  id,
  children,
}: PropsWithChildren<QuoteItemsSortableProps>) {
  const {
    attributes,
    isDragging,
    listeners,
    setNodeRef,
    setActivatorNodeRef,
    transform,
    transition,
  } = useSortable({
    animateLayoutChanges,
    id,
  });

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

  const context = useMemo(
    () => ({
      attributes,
      listeners,
      ref: setActivatorNodeRef,
    }),
    [attributes, listeners, setActivatorNodeRef]
  );

  return (
    <QuoteItemsSortableTableRowContext.Provider value={context}>
      <TableRow
        key={id}
        id={String(id)}
        className={cn(
          isDragging ? "opacity-40" : "opacity-100",
          "m-0 hover:bg-muted hover:focus-within:bg-accent focus-within:bg-accent"
        )}
        ref={setNodeRef}
        style={style}
      >
        {children}
      </TableRow>
    </QuoteItemsSortableTableRowContext.Provider>
  );
}
