"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Plus } from "lucide-react";
import { fetchCustomFieldFormStructure } from "@open-mercato/ui/backend/utils/customFieldForms";
import { LinkButton } from "@open-mercato/ui/primitives/link-button";
import { Spinner } from "@open-mercato/ui/primitives/spinner";
import { E } from "../../../../../generated/entities.ids.generated.js";
import { DealCustomFieldControl } from "./dealCustomFieldControl.js";
function ManageFieldsLink({ href, label }) {
  return /* @__PURE__ */ jsx(LinkButton, { asChild: true, variant: "gray", size: "sm", children: /* @__PURE__ */ jsxs("a", { href, className: "inline-flex items-center gap-1", children: [
    /* @__PURE__ */ jsx(Plus, { className: "size-3.5" }),
    label
  ] }) });
}
function DealCustomAttributes({
  values,
  onChange,
  errors,
  disabled = false,
  manageHref,
  labels,
  onLoaded
}) {
  const [fields, setFields] = React.useState([]);
  const [isLoading, setIsLoading] = React.useState(true);
  const onLoadedRef = React.useRef(onLoaded);
  React.useEffect(() => {
    onLoadedRef.current = onLoaded;
  }, [onLoaded]);
  React.useEffect(() => {
    let cancelled = false;
    setIsLoading(true);
    fetchCustomFieldFormStructure([E.customers.customer_deal]).then((result) => {
      if (cancelled) return;
      setFields(result.fields);
      setIsLoading(false);
      onLoadedRef.current?.({ fields: result.fields, definitions: result.definitions });
    }).catch(() => {
      if (cancelled) return;
      setFields([]);
      setIsLoading(false);
      onLoadedRef.current?.({ fields: [], definitions: [] });
    });
    return () => {
      cancelled = true;
    };
  }, []);
  if (isLoading) {
    return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-sm text-muted-foreground", children: [
      /* @__PURE__ */ jsx(Spinner, { className: "size-4" }),
      labels.loading
    ] });
  }
  if (fields.length === 0) {
    return /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
      /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: labels.empty }),
      /* @__PURE__ */ jsx(ManageFieldsLink, { href: manageHref, label: labels.manage })
    ] });
  }
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
    fields.map((field) => /* @__PURE__ */ jsx(
      DealCustomFieldControl,
      {
        field,
        value: values[field.id],
        onChange: (next) => onChange(field.id, next),
        error: errors?.[field.id],
        disabled
      },
      field.id
    )),
    /* @__PURE__ */ jsx("div", { className: "pt-1", children: /* @__PURE__ */ jsx(ManageFieldsLink, { href: manageHref, label: labels.manage }) })
  ] });
}
var DealCustomAttributes_default = DealCustomAttributes;
export {
  DealCustomAttributes,
  DealCustomAttributes_default as default
};
//# sourceMappingURL=DealCustomAttributes.js.map
