import {
  ATTRIBUTE_DETAIL_FIELDS
} from "./chunk-LO7XX5M7.js";
import {
  RouteFocusModal,
  useRouteModal
} from "./chunk-OV7R2AH5.js";
import "./chunk-3QSRE5LS.js";
import {
  attributesQueryKeys,
  useAttribute,
  useCreateAttributePossibleValue
} 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-create-possible-value/attribute-create-possible-value.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, XMark, Tag } from "@medusajs/icons";
import {
  Button,
  Heading,
  IconButton,
  Input,
  ProgressTabs,
  Text,
  toast
} from "@medusajs/ui";
import { useFieldArray, useForm, useFormContext, FormProvider } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { useParams } from "react-router-dom";
import { jsx, jsxs } from "react/jsx-runtime";
var SortableValueInput = ({
  id,
  index,
  onRemove
}) => {
  const { t } = useTranslation();
  const { register } = useFormContext();
  const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id });
  const style = {
    transform: CSS.Transform.toString(transform),
    transition
  };
  return /* @__PURE__ */ jsxs(
    "div",
    {
      ref: setNodeRef,
      style,
      className: "flex items-center gap-2 p-2 bg-ui-bg-component border border-ui-border-base rounded-xl mb-2",
      "data-testid": `create-possible-value-input-item-${index}`,
      children: [
        /* @__PURE__ */ jsx(
          "button",
          {
            type: "button",
            className: "cursor-grab active:cursor-grabbing",
            ...attributes,
            ...listeners,
            "data-testid": `create-possible-value-drag-handle-${index}`,
            children: /* @__PURE__ */ jsx(DotsSix, { className: "text-ui-fg-subtle" })
          }
        ),
        /* @__PURE__ */ jsx("div", { className: "flex-1", children: /* @__PURE__ */ jsx(
          Input,
          {
            className: "flex-1",
            placeholder: t("attributes.createPossibleValues.enterValue"),
            ...register(`new_values.${index}.value`),
            "data-testid": `create-possible-value-input-${index}`
          }
        ) }),
        /* @__PURE__ */ jsx(
          IconButton,
          {
            variant: "transparent",
            size: "small",
            type: "button",
            onClick: onRemove,
            "data-testid": `create-possible-value-remove-button-${index}`,
            children: /* @__PURE__ */ jsx(XMark, {})
          }
        )
      ]
    }
  );
};
var SortableRankingItem = ({
  id,
  value,
  index
}) => {
  const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id });
  const style = {
    transform: CSS.Transform.toString(transform),
    transition
  };
  return /* @__PURE__ */ jsxs(
    "div",
    {
      ref: setNodeRef,
      style,
      className: "flex items-center gap-3 p-3 bg-ui-bg-component border border-ui-border-base rounded-xl mb-2",
      "data-testid": `ranking-item-${index}`,
      children: [
        /* @__PURE__ */ jsx(
          "button",
          {
            type: "button",
            className: "cursor-grab active:cursor-grabbing",
            ...attributes,
            ...listeners,
            "data-testid": `ranking-item-drag-handle-${index}`,
            children: /* @__PURE__ */ jsx(DotsSix, { className: "text-ui-fg-subtle" })
          }
        ),
        /* @__PURE__ */ jsx(Tag, { className: "text-ui-fg-subtle" }),
        /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", children: value })
      ]
    }
  );
};
var AttributeCreatePossibleValueInner = () => {
  const { t } = useTranslation();
  const { id } = useParams();
  const { handleSuccess } = useRouteModal();
  const { attribute, isPending: isAttributeLoading } = useAttribute(id, {
    fields: ATTRIBUTE_DETAIL_FIELDS
  });
  const { mutateAsync: createValue } = useCreateAttributePossibleValue(id);
  const [activeTab, setActiveTab] = useState(
    "values"
  );
  const [tabStatuses, setTabStatuses] = useState({
    valuesStatus: "not-started",
    organizeStatus: "not-started"
  });
  const [rankingItems, setRankingItems] = useState([]);
  const [isSaving, setIsSaving] = useState(false);
  const form = useForm({
    defaultValues: {
      new_values: [{ id: crypto.randomUUID(), value: "" }]
    }
  });
  const { fields, append, remove } = useFieldArray({
    control: form.control,
    name: "new_values"
  });
  const sensors = useSensors(
    useSensor(PointerSensor),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates
    })
  );
  const handleValuesDragEnd = (event) => {
    const { active, over } = event;
    if (over && active.id !== over.id) {
      const oldIndex = fields.findIndex((field) => field.id === active.id);
      const newIndex = fields.findIndex((field) => field.id === over.id);
      const currentValues = form.getValues("new_values");
      const reordered = arrayMove(currentValues, oldIndex, newIndex);
      reordered.forEach((item, idx) => {
        form.setValue(`new_values.${idx}.id`, item.id);
        form.setValue(`new_values.${idx}.value`, item.value);
      });
    }
  };
  const handleRankingDragEnd = (event) => {
    const { active, over } = event;
    if (over && active.id !== over.id) {
      setRankingItems((items) => {
        const oldIndex = items.findIndex((item) => item.id === active.id);
        const newIndex = items.findIndex((item) => item.id === over.id);
        return arrayMove(items, oldIndex, newIndex);
      });
    }
  };
  const handleAddValue = () => {
    append({ id: crypto.randomUUID(), value: "" });
    setTabStatuses((prev) => ({
      ...prev,
      valuesStatus: "in-progress"
    }));
  };
  const handleContinue = () => {
    const newValues = form.getValues("new_values").filter((v) => v.value.trim() !== "");
    if (newValues.length === 0) {
      toast.warning(t("attributes.createPossibleValues.enterValue"));
      return;
    }
    const existingValues = (attribute?.possible_values ?? []).slice().sort((a, b) => (a.rank ?? 0) - (b.rank ?? 0)).map((pv) => ({
      id: pv.id,
      value: pv.value,
      isNew: false
    }));
    const newRankingItems = newValues.map((nv) => ({
      id: nv.id,
      value: nv.value,
      isNew: true
    }));
    setRankingItems([...existingValues, ...newRankingItems]);
    setTabStatuses({
      valuesStatus: "completed",
      organizeStatus: "in-progress"
    });
    setActiveTab("organize-ranking");
  };
  const handleTabChange = (value) => {
    const newTab = value;
    if (newTab === "organize-ranking" && tabStatuses.valuesStatus !== "completed") {
      return;
    }
    setActiveTab(newTab);
  };
  const handleSave = async () => {
    setIsSaving(true);
    try {
      for (const [index, item] of rankingItems.entries()) {
        if (item.isNew) {
          await createValue({
            value: item.value,
            rank: index + 1,
            metadata: {}
          });
        }
      }
      for (const [index, item] of rankingItems.entries()) {
        if (!item.isNew) {
          const existingPV = (attribute?.possible_values ?? []).find(
            (pv) => pv.id === item.id
          );
          if (existingPV && existingPV.rank !== index + 1) {
            await sdk.admin.attributes.$id.values.$valueId.mutate({
              $id: id,
              $valueId: item.id,
              rank: index + 1
            });
          }
        }
      }
      queryClient.invalidateQueries({
        queryKey: attributesQueryKeys.detail(id)
      });
      toast.success(t("attributes.createPossibleValues.successToast"));
      handleSuccess(`/settings/attributes/${id}`);
    } catch (error) {
      toast.error(error.message);
    } finally {
      setIsSaving(false);
    }
  };
  if (isAttributeLoading || !attribute) {
    return null;
  }
  return /* @__PURE__ */ jsx(FormProvider, { ...form, children: /* @__PURE__ */ jsxs(
    ProgressTabs,
    {
      value: activeTab,
      onValueChange: handleTabChange,
      className: "flex size-full flex-col overflow-hidden",
      "data-testid": "attribute-create-possible-value-progress-tabs",
      children: [
        /* @__PURE__ */ jsx(RouteFocusModal.Header, { "data-testid": "attribute-create-possible-value-modal-header", children: /* @__PURE__ */ jsxs(
          ProgressTabs.List,
          {
            className: "justify-start flex w-full items-center",
            "data-testid": "attribute-create-possible-value-tabs-list",
            children: [
              /* @__PURE__ */ jsx(
                ProgressTabs.Trigger,
                {
                  value: "values",
                  status: tabStatuses.valuesStatus,
                  "data-testid": "attribute-create-possible-value-values-tab",
                  children: t("attributes.createPossibleValues.tabs.values")
                }
              ),
              /* @__PURE__ */ jsx(
                ProgressTabs.Trigger,
                {
                  value: "organize-ranking",
                  status: tabStatuses.organizeStatus,
                  "data-testid": "attribute-create-possible-value-organize-tab",
                  children: t("attributes.createPossibleValues.tabs.organizeRanking")
                }
              )
            ]
          }
        ) }),
        /* @__PURE__ */ jsx(
          RouteFocusModal.Body,
          {
            className: "flex flex-1 justify-center overflow-auto px-6 py-16",
            "data-testid": "attribute-create-possible-value-modal-body",
            children: /* @__PURE__ */ jsxs("div", { className: "flex w-full max-w-[720px] flex-col gap-y-8", children: [
              /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-1", children: [
                /* @__PURE__ */ jsx(RouteFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx(Heading, { "data-testid": "attribute-create-possible-value-heading", children: t("attributes.createPossibleValues.header") }) }),
                /* @__PURE__ */ jsx(RouteFocusModal.Description, { asChild: true, children: /* @__PURE__ */ jsx(
                  Text,
                  {
                    size: "small",
                    className: "text-ui-fg-subtle",
                    "data-testid": "attribute-create-possible-value-subtitle",
                    children: t("attributes.createPossibleValues.subtitle", {
                      name: attribute.name
                    })
                  }
                ) })
              ] }),
              /* @__PURE__ */ jsx(ProgressTabs.Content, { value: "values", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-4", children: [
                /* @__PURE__ */ jsx(
                  DndContext,
                  {
                    sensors,
                    collisionDetection: closestCenter,
                    onDragEnd: handleValuesDragEnd,
                    children: /* @__PURE__ */ jsx(
                      SortableContext,
                      {
                        items: fields.map((field) => field.id),
                        strategy: verticalListSortingStrategy,
                        children: fields.map((field, index) => /* @__PURE__ */ jsx(
                          SortableValueInput,
                          {
                            id: field.id,
                            index,
                            onRemove: () => remove(index)
                          },
                          field.id
                        ))
                      }
                    )
                  }
                ),
                /* @__PURE__ */ jsx(
                  Button,
                  {
                    type: "button",
                    variant: "secondary",
                    size: "small",
                    onClick: handleAddValue,
                    "data-testid": "attribute-create-possible-value-add-button",
                    children: t("attributes.createPossibleValues.addValue")
                  }
                )
              ] }) }),
              /* @__PURE__ */ jsx(ProgressTabs.Content, { value: "organize-ranking", children: /* @__PURE__ */ jsx(
                DndContext,
                {
                  sensors,
                  collisionDetection: closestCenter,
                  onDragEnd: handleRankingDragEnd,
                  children: /* @__PURE__ */ jsx(
                    SortableContext,
                    {
                      items: rankingItems.map((item) => item.id),
                      strategy: verticalListSortingStrategy,
                      children: rankingItems.map((item, index) => /* @__PURE__ */ jsx(
                        SortableRankingItem,
                        {
                          id: item.id,
                          value: item.value,
                          index
                        },
                        item.id
                      ))
                    }
                  )
                }
              ) })
            ] })
          }
        ),
        /* @__PURE__ */ jsx(RouteFocusModal.Footer, { "data-testid": "attribute-create-possible-value-modal-footer", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-2", children: [
          /* @__PURE__ */ jsx(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx(
            Button,
            {
              size: "small",
              variant: "secondary",
              type: "button",
              "data-testid": "attribute-create-possible-value-cancel-button",
              children: t("actions.cancel")
            }
          ) }),
          activeTab === "values" ? /* @__PURE__ */ jsx(
            Button,
            {
              size: "small",
              type: "button",
              onClick: handleContinue,
              "data-testid": "attribute-create-possible-value-continue-button",
              children: t("actions.continue")
            }
          ) : /* @__PURE__ */ jsx(
            Button,
            {
              size: "small",
              type: "button",
              onClick: handleSave,
              isLoading: isSaving,
              "data-testid": "attribute-create-possible-value-save-button",
              children: t("actions.save")
            }
          )
        ] }) })
      ]
    }
  ) });
};
var AttributeCreatePossibleValue = () => {
  return /* @__PURE__ */ jsx(RouteFocusModal, { "data-testid": "attribute-create-possible-value-modal", children: /* @__PURE__ */ jsx(AttributeCreatePossibleValueInner, {}) });
};
export {
  AttributeCreatePossibleValue as Component
};
