import { DraggableSyntheticListeners } from "@dnd-kit/core";
import { defaultAnimateLayoutChanges, useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { TableRow } from "@repo/shadcn-ui/components";
import { cn } from "@repo/shadcn-ui/lib/utils";
import { CSSProperties, PropsWithChildren, createContext, useMemo } from "react";
import { CustomerInvoiceItemsSortableProps } from "./customer-invoice-items-sortable-datatable";

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

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

  return true;
}

export function CustomerInvoiceItemsSortableTableRow({
  id,
  children,
}: PropsWithChildren<CustomerInvoiceItemsSortableProps>) {
  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 (
    <CustomerInvoiceItemsSortableTableRowContext.Provider value={context}>
      <TableRow
        key={id}
        id={String(id)}
        className={cn(
          isDragging ? "opacity-60" : "opacity-100",
          "m-0 hover:bg-muted hover:focus-within:bg-accent focus-within:bg-accent"
        )}
        ref={setNodeRef}
        style={style}
      >
        {children}
      </TableRow>
    </CustomerInvoiceItemsSortableTableRowContext.Provider>
  );
}
