import {
  ATTRIBUTE_DETAIL_FIELDS
} from "./chunk-LO7XX5M7.js";
import {
  UpdatePossibleValueSchema
} from "./chunk-4ZTZTIIM.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-U2ZFCAPX.js";
import {
  ActionMenu
} from "./chunk-BDGZ4EQO.js";
import "./chunk-LAVHRER2.js";
import "./chunk-Y7QKP6QU.js";
import {
  RouteDrawer,
  useRouteModal
} from "./chunk-FWJLS7XD.js";
import {
  Form
} from "./chunk-3QSRE5LS.js";
import {
  useAttribute,
  useUpdateAttributePossibleValue
} from "./chunk-7O5NDICV.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import "./chunk-ZBWL72TB.js";
import "./chunk-NBMM2TZK.js";

// src/pages/attributes/attribute-edit-possible-value/attribute-edit-possible-value.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import { Button, Heading, Input, Text, toast } from "@medusajs/ui";
import { useEffect, useRef } from "react";
import { useFieldArray, useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { useParams, useSearchParams } from "react-router-dom";
import { Trash } from "@medusajs/icons";
import { jsx, jsxs } from "react/jsx-runtime";
var EditPossibleValueForm = ({
  attributeId,
  possibleValue
}) => {
  const { t } = useTranslation();
  const { handleSuccess } = useRouteModal();
  const originalMetadataRef = useRef({});
  const { mutateAsync, isPending: isMutating } = useUpdateAttributePossibleValue(attributeId, possibleValue.id);
  const form = useForm({
    resolver: zodResolver(UpdatePossibleValueSchema),
    defaultValues: {
      value: "",
      rank: void 0,
      metadata: []
    }
  });
  const { fields, append, remove } = useFieldArray({
    control: form.control,
    name: "metadata"
  });
  useEffect(() => {
    if (possibleValue) {
      const originalMetadata = possibleValue.metadata || {};
      originalMetadataRef.current = originalMetadata;
      const metadataArray = Object.entries(originalMetadata).map(
        ([key, value]) => ({ key, value: String(value) })
      );
      form.reset({
        value: possibleValue.value,
        rank: possibleValue.rank,
        metadata: metadataArray.length > 0 ? metadataArray : [{ key: "", value: "" }]
      });
    }
  }, [possibleValue, form]);
  const handleSubmit = form.handleSubmit(async (data) => {
    const transformedMetadata = data.metadata.reduce(
      (acc, item) => {
        if (item.key.trim() !== "" && item.value.trim() !== "") {
          acc[item.key] = item.value;
        }
        return acc;
      },
      {}
    );
    const finalMetadata = { ...transformedMetadata };
    const originalKeys = Object.keys(originalMetadataRef.current);
    const newKeys = Object.keys(transformedMetadata);
    originalKeys.forEach((key) => {
      if (!newKeys.includes(key)) {
        finalMetadata[key] = "";
      }
    });
    await mutateAsync(
      {
        value: data.value,
        rank: data.rank,
        metadata: finalMetadata
      },
      {
        onSuccess: () => {
          toast.success(
            t("attributes.editPossibleValue.successToast", {
              value: data.value
            })
          );
          handleSuccess();
        },
        onError: (err) => {
          toast.error(err.message);
        }
      }
    );
  });
  return /* @__PURE__ */ jsx(RouteDrawer.Form, { form, "data-testid": "attribute-edit-possible-value-form", children: /* @__PURE__ */ jsxs(
    KeyboundForm,
    {
      className: "flex size-full flex-col overflow-hidden",
      onSubmit: handleSubmit,
      children: [
        /* @__PURE__ */ jsxs(
          RouteDrawer.Body,
          {
            className: "flex flex-1 flex-col gap-y-6 overflow-auto",
            "data-testid": "attribute-edit-possible-value-form-body",
            children: [
              /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-4", children: [
                /* @__PURE__ */ jsx(
                  Form.Field,
                  {
                    control: form.control,
                    name: "value",
                    render: ({ field }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
                      /* @__PURE__ */ jsx(Form.Label, { children: t("attributes.fields.value") }),
                      /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(Input, { ...field }) }),
                      /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                    ] })
                  }
                ),
                /* @__PURE__ */ jsx(
                  Form.Field,
                  {
                    control: form.control,
                    name: "rank",
                    render: ({ field }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
                      /* @__PURE__ */ jsx(Form.Label, { optional: true, children: t("attributes.fields.rank") }),
                      /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(
                        Input,
                        {
                          ...field,
                          type: "number",
                          value: field.value ?? "",
                          onChange: (e) => field.onChange(
                            e.target.value === "" ? void 0 : Number(e.target.value)
                          )
                        }
                      ) }),
                      /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                    ] })
                  }
                )
              ] }),
              /* @__PURE__ */ jsxs("div", { children: [
                /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", className: "mb-2", children: t("attributes.fields.metadata") }),
                /* @__PURE__ */ jsxs("table", { className: "w-full overflow-hidden rounded-lg border-separate border-spacing-0 border", children: [
                  /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { className: "bg-ui-bg-subtle", children: [
                    /* @__PURE__ */ jsx("th", { className: "border-b border-r px-3 py-2 text-left", children: /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", children: t("fields.key") }) }),
                    /* @__PURE__ */ jsx("th", { className: "border-b px-3 py-2 text-left", children: /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", children: t("attributes.fields.value") }) }),
                    /* @__PURE__ */ jsx("th", { className: "w-10 border-b" })
                  ] }) }),
                  /* @__PURE__ */ jsx("tbody", { children: fields.map((field, index) => /* @__PURE__ */ jsxs("tr", { className: "border-b last:border-b-0", children: [
                    /* @__PURE__ */ jsx("td", { className: "border-r px-3 py-2", children: /* @__PURE__ */ jsx(
                      "input",
                      {
                        placeholder: "Key",
                        className: "w-full bg-transparent text-sm outline-none",
                        ...form.register(`metadata.${index}.key`)
                      }
                    ) }),
                    /* @__PURE__ */ jsx("td", { className: "px-3 py-2", children: /* @__PURE__ */ jsx(
                      "input",
                      {
                        placeholder: "Value",
                        className: "w-full bg-transparent text-sm outline-none",
                        ...form.register(`metadata.${index}.value`)
                      }
                    ) }),
                    /* @__PURE__ */ jsx("td", { className: "px-1", children: /* @__PURE__ */ jsx(
                      ActionMenu,
                      {
                        groups: [
                          {
                            actions: [
                              {
                                label: t("actions.delete"),
                                onClick: () => remove(index),
                                icon: /* @__PURE__ */ jsx(Trash, {})
                              }
                            ]
                          }
                        ]
                      }
                    ) })
                  ] }, field.id)) }),
                  /* @__PURE__ */ jsx("tfoot", { children: /* @__PURE__ */ jsx("tr", { children: /* @__PURE__ */ jsx("td", { colSpan: 3, className: "border-t p-3", children: /* @__PURE__ */ jsx(
                    Button,
                    {
                      type: "button",
                      variant: "secondary",
                      size: "small",
                      className: "w-full",
                      onClick: () => append({ key: "", value: "" }),
                      children: "+ Add Row"
                    }
                  ) }) }) })
                ] })
              ] })
            ]
          }
        ),
        /* @__PURE__ */ jsx(RouteDrawer.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
          /* @__PURE__ */ jsx(RouteDrawer.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { variant: "secondary", size: "small", type: "button", children: t("actions.cancel") }) }),
          /* @__PURE__ */ jsx(Button, { size: "small", type: "submit", isLoading: isMutating, children: t("actions.save") })
        ] }) })
      ]
    }
  ) });
};
var AttributeEditPossibleValue = () => {
  const { id } = useParams();
  const [searchParams] = useSearchParams();
  const { t } = useTranslation();
  const possibleValueId = searchParams.get("possible_value_id");
  const { attribute, isPending, isError, error } = useAttribute(id, {
    fields: ATTRIBUTE_DETAIL_FIELDS
  });
  if (isError) {
    throw error;
  }
  if (isPending || !attribute) {
    return null;
  }
  const possibleValue = attribute.possible_values?.find(
    (pv) => pv.id === possibleValueId
  );
  if (!possibleValue) {
    return null;
  }
  return /* @__PURE__ */ jsxs(RouteDrawer, { "data-testid": "attribute-edit-possible-value-drawer", children: [
    /* @__PURE__ */ jsxs(RouteDrawer.Header, { children: [
      /* @__PURE__ */ jsx(RouteDrawer.Title, { asChild: true, children: /* @__PURE__ */ jsx(Heading, { children: t("attributes.editPossibleValue.header") }) }),
      /* @__PURE__ */ jsx(RouteDrawer.Description, { className: "sr-only", children: t("attributes.editPossibleValue.subtitle") })
    ] }),
    /* @__PURE__ */ jsx(
      EditPossibleValueForm,
      {
        attributeId: id,
        possibleValue
      }
    )
  ] });
};
export {
  AttributeEditPossibleValue as Component
};
