import {
  ATTRIBUTE_DETAIL_FIELDS
} from "./chunk-LO7XX5M7.js";
import {
  RouteFocusModal,
  useRouteModal
} from "./chunk-OV7R2AH5.js";
import "./chunk-3QSRE5LS.js";
import {
  attributesQueryKeys,
  useAttribute
} from "./chunk-XMVTX2EN.js";
import {
  queryClient
} from "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import {
  sdk
} from "./chunk-RIN4CBRB.js";
import "./chunk-NBMM2TZK.js";

// src/pages/attributes/attribute-edit-ranking/attribute-edit-ranking.tsx
import { useState } from "react";
import {
  DndContext,
  closestCenter,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors
} from "@dnd-kit/core";
import {
  arrayMove,
  SortableContext,
  sortableKeyboardCoordinates,
  useSortable,
  verticalListSortingStrategy
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { DotsSix, Tag } from "@medusajs/icons";
import { Button, Text, toast } from "@medusajs/ui";
import { useTranslation } from "react-i18next";
import { useParams } from "react-router-dom";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
var SortableRankingItem = ({ item }) => {
  const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id: item.id });
  const style = {
    transform: CSS.Transform.toString(transform),
    transition
  };
  return /* @__PURE__ */ jsxs(
    "div",
    {
      ref: setNodeRef,
      style,
      className: "flex items-center gap-x-3 border-b px-6 py-3 last:border-b-0",
      children: [
        /* @__PURE__ */ jsx(
          "button",
          {
            type: "button",
            className: "cursor-grab text-ui-fg-muted",
            ...attributes,
            ...listeners,
            children: /* @__PURE__ */ jsx(DotsSix, {})
          }
        ),
        /* @__PURE__ */ jsx(Tag, { className: "text-ui-fg-interactive" }),
        /* @__PURE__ */ jsx(Text, { size: "small", children: item.value })
      ]
    }
  );
};
var EditRankingInner = () => {
  const { id } = useParams();
  const { t } = useTranslation();
  const { handleSuccess } = useRouteModal();
  const { attribute, isPending: isLoading } = useAttribute(id, {
    fields: ATTRIBUTE_DETAIL_FIELDS
  });
  const existingValues = (attribute?.possible_values ?? []).sort((a, b) => (a.rank ?? 0) - (b.rank ?? 0)).map((v) => ({
    id: v.id,
    value: v.value,
    rank: v.rank
  }));
  const [items, setItems] = useState([]);
  const [initialized, setInitialized] = useState(false);
  if (!initialized && existingValues.length > 0) {
    setItems(existingValues);
    setInitialized(true);
  }
  const sensors = useSensors(
    useSensor(PointerSensor),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates
    })
  );
  const handleDragEnd = (event) => {
    const { active, over } = event;
    if (!over || active.id === over.id) return;
    setItems((prev) => {
      const oldIndex = prev.findIndex((item) => item.id === active.id);
      const newIndex = prev.findIndex((item) => item.id === over.id);
      return arrayMove(prev, oldIndex, newIndex);
    });
  };
  const [isSaving, setIsSaving] = useState(false);
  const handleSave = async () => {
    setIsSaving(true);
    try {
      const updates = items.map((item, index) => ({
        id: item.id,
        newRank: index + 1,
        oldRank: existingValues.find((v) => v.id === item.id)?.rank
      })).filter((u) => u.newRank !== u.oldRank);
      for (const update of updates) {
        await sdk.admin.attributes.$id.values.$valueId.mutate({
          $id: id,
          $valueId: update.id,
          rank: update.newRank
        });
      }
      queryClient.invalidateQueries({
        queryKey: attributesQueryKeys.detail(id)
      });
      toast.success(t("attributes.editRanking.successToast", "Ranking updated successfully."));
      handleSuccess();
    } catch (err) {
      toast.error(err.message);
    } finally {
      setIsSaving(false);
    }
  };
  if (isLoading || !attribute) {
    return null;
  }
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(RouteFocusModal.Header, {}),
    /* @__PURE__ */ jsx(RouteFocusModal.Body, { className: "flex flex-1 flex-col overflow-auto", children: /* @__PURE__ */ jsx(
      DndContext,
      {
        sensors,
        collisionDetection: closestCenter,
        onDragEnd: handleDragEnd,
        children: /* @__PURE__ */ jsx(
          SortableContext,
          {
            items: items.map((i) => i.id),
            strategy: verticalListSortingStrategy,
            children: items.map((item) => /* @__PURE__ */ jsx(SortableRankingItem, { item }, item.id))
          }
        )
      }
    ) }),
    /* @__PURE__ */ jsx(RouteFocusModal.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
      /* @__PURE__ */ jsx(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { variant: "secondary", size: "small", children: t("actions.cancel") }) }),
      /* @__PURE__ */ jsx(
        Button,
        {
          size: "small",
          onClick: handleSave,
          isLoading: isSaving,
          children: t("actions.save")
        }
      )
    ] }) })
  ] });
};
var AttributeEditRanking = () => {
  return /* @__PURE__ */ jsx(RouteFocusModal, { children: /* @__PURE__ */ jsx(EditRankingInner, {}) });
};
export {
  AttributeEditRanking as Component
};
