"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { CrudForm } from "@open-mercato/ui/backend/CrudForm";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { DictionarySelectControl } from "@open-mercato/core/modules/dictionaries/components/DictionarySelectControl";
import { AppearanceSelector } from "@open-mercato/core/modules/dictionaries/components/AppearanceSelector";
import { AttachmentsSection, TagsSection } from "@open-mercato/ui/backend/detail";
import { Button } from "@open-mercato/ui/primitives/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "@open-mercato/ui/primitives/select";
import { E } from "../../../generated/entities.ids.generated.js";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { RESOURCES_CAPACITY_UNIT_DICTIONARY_KEY } from "@open-mercato/core/modules/resources/lib/capacityUnits";
import { RESOURCES_RESOURCE_FIELDSET_DEFAULT, resolveResourcesResourceFieldsetCode } from "@open-mercato/core/modules/resources/lib/resourceCustomFields";
import Link from "next/link";
import { Plus, Settings } from "lucide-react";
const DEFAULT_PAGE_SIZE = 100;
function useResourcesResourceFormConfig(options = {}) {
  const { selectedCapacityUnit, selectedResourceTypeId, tagsSection } = options;
  const t = useT();
  const scopeVersion = useOrganizationScopeVersion();
  const [resourceTypes, setResourceTypes] = React.useState([]);
  const [resourceTypesLoaded, setResourceTypesLoaded] = React.useState(false);
  const [capacityUnitDictionaryId, setCapacityUnitDictionaryId] = React.useState(null);
  React.useEffect(() => {
    let cancelled = false;
    async function loadResourceTypes() {
      try {
        const params = new URLSearchParams({ page: "1", pageSize: String(DEFAULT_PAGE_SIZE) });
        const call = await apiCall(`/api/resources/resource-types?${params.toString()}`);
        if (!cancelled) {
          const items = Array.isArray(call.result?.items) ? call.result.items : [];
          setResourceTypes(items);
        }
      } catch {
        if (!cancelled) setResourceTypes([]);
      } finally {
        if (!cancelled) setResourceTypesLoaded(true);
      }
    }
    loadResourceTypes();
    return () => {
      cancelled = true;
    };
  }, [scopeVersion]);
  React.useEffect(() => {
    const selectedId = typeof selectedResourceTypeId === "string" && selectedResourceTypeId.trim().length ? selectedResourceTypeId.trim() : null;
    if (!selectedId) return;
    if (resourceTypes.some((type) => type.id === selectedId)) return;
    const selectedResourceTypeLookupId = selectedId;
    let cancelled = false;
    async function loadSelectedResourceType() {
      try {
        const call = await apiCall(
          `/api/resources/resource-types?ids=${encodeURIComponent(selectedResourceTypeLookupId)}&pageSize=1`
        );
        const entry = Array.isArray(call.result?.items) ? call.result.items[0] : null;
        const entryId = typeof entry?.id === "string" ? entry.id : null;
        const entryName = typeof entry?.name === "string" ? entry.name : null;
        if (!entryId || !entryName) return;
        if (!cancelled) {
          setResourceTypes((prev) => {
            if (prev.some((type) => type.id === entryId)) return prev;
            return [{ id: entryId, name: entryName }, ...prev];
          });
        }
      } catch {
        if (!cancelled) setResourceTypes((prev) => prev);
      }
    }
    loadSelectedResourceType();
    return () => {
      cancelled = true;
    };
  }, [resourceTypes, selectedResourceTypeId]);
  React.useEffect(() => {
    let cancelled = false;
    async function loadCapacityUnitDictionary() {
      try {
        const call = await apiCall("/api/dictionaries");
        const items = Array.isArray(call.result?.items) ? call.result.items : [];
        const matches = items.filter((item) => item?.key === RESOURCES_CAPACITY_UNIT_DICTIONARY_KEY);
        const preferred = matches.find((item) => item?.isInherited === false) ?? matches[0] ?? null;
        if (!cancelled) setCapacityUnitDictionaryId(preferred?.id ?? null);
      } catch {
        if (!cancelled) setCapacityUnitDictionaryId(null);
      }
    }
    loadCapacityUnitDictionary();
    return () => {
      cancelled = true;
    };
  }, [scopeVersion]);
  const resourceFieldsetByTypeId = React.useMemo(() => {
    const map = /* @__PURE__ */ new Map();
    resourceTypes.forEach((type) => {
      map.set(type.id, resolveResourcesResourceFieldsetCode(type.name));
    });
    return map;
  }, [resourceTypes]);
  const resolveFieldsetCode = React.useCallback((resourceTypeId) => {
    if (!resourceTypeId) return RESOURCES_RESOURCE_FIELDSET_DEFAULT;
    return resourceFieldsetByTypeId.get(resourceTypeId) ?? RESOURCES_RESOURCE_FIELDSET_DEFAULT;
  }, [resourceFieldsetByTypeId]);
  const appearanceLabels = React.useMemo(() => ({
    colorLabel: t("resources.resources.form.appearance.colorLabel", "Color"),
    colorHelp: t("resources.resources.form.appearance.colorHelp", "Pick a color for this resource."),
    colorClearLabel: t("resources.resources.form.appearance.colorClear", "Clear color"),
    iconLabel: t("resources.resources.form.appearance.iconLabel", "Icon"),
    iconPlaceholder: t("resources.resources.form.appearance.iconPlaceholder", "Type an emoji or icon name"),
    iconPickerTriggerLabel: t("resources.resources.form.appearance.iconPicker", "Browse icons"),
    iconSearchPlaceholder: t("resources.resources.form.appearance.iconSearch", "Search icons or emojis\u2026"),
    iconSearchEmptyLabel: t("resources.resources.form.appearance.iconSearchEmpty", "No icons match your search"),
    iconSuggestionsLabel: t("resources.resources.form.appearance.iconSuggestions", "Suggestions"),
    iconClearLabel: t("resources.resources.form.appearance.iconClear", "Clear icon"),
    previewEmptyLabel: t("resources.resources.form.appearance.previewEmpty", "No appearance selected")
  }), [t]);
  const fields = React.useMemo(() => {
    const baseFields = [
      { id: "name", label: t("resources.resources.form.fields.name", "Name"), type: "text", required: true },
      {
        id: "description",
        label: t("resources.resources.form.fields.description", "Description"),
        type: "richtext",
        editor: "uiw"
      },
      {
        id: "resourceTypeId",
        label: t("resources.resources.form.fields.type", "Resource type"),
        type: "custom",
        component: ({ value, setValue, setFormValue, disabled }) => {
          const selectedValue = typeof value === "string" ? value : "";
          const selectedOption = resourceTypes.find((type) => type.id === selectedValue);
          const optionsKey = resourceTypes.map((type) => `${type.id}:${type.name}`).join("\0");
          return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsxs(
              Select,
              {
                value: selectedValue,
                onValueChange: (next) => {
                  const value2 = next || "";
                  setValue(value2);
                  if (setFormValue) {
                    setFormValue("customFieldsetCode", resolveFieldsetCode(value2 || null));
                  }
                },
                disabled,
                children: [
                  /* @__PURE__ */ jsx(SelectTrigger, { "data-crud-focus-target": "", children: /* @__PURE__ */ jsx(SelectValue, { placeholder: t("ui.forms.select.emptyOption", "\u2014"), children: selectedOption?.name }) }),
                  /* @__PURE__ */ jsx(SelectContent, { children: resourceTypes.map((type) => /* @__PURE__ */ jsx(SelectItem, { value: type.id, children: type.name }, type.id)) })
                ]
              },
              `resource-type:${selectedValue}:${optionsKey}`
            ),
            /* @__PURE__ */ jsx(
              Button,
              {
                asChild: true,
                type: "button",
                variant: "ghost",
                size: "icon",
                className: "shrink-0",
                title: t("resources.resources.form.fields.type.manage", "Manage resource types"),
                "aria-label": t("resources.resources.form.fields.type.manage", "Manage resource types"),
                disabled,
                children: /* @__PURE__ */ jsx(Link, { href: "/backend/resources/resource-types", children: /* @__PURE__ */ jsx(Settings, { className: "h-4 w-4", "aria-hidden": true }) })
              }
            ),
            /* @__PURE__ */ jsx(
              Button,
              {
                asChild: true,
                type: "button",
                variant: "ghost",
                size: "icon",
                className: "shrink-0",
                title: t("resources.resources.form.fields.type.add", "Add resource type"),
                "aria-label": t("resources.resources.form.fields.type.add", "Add resource type"),
                disabled,
                children: /* @__PURE__ */ jsx(Link, { href: "/backend/resources/resource-types/create", children: /* @__PURE__ */ jsx(Plus, { className: "h-4 w-4", "aria-hidden": true }) })
              }
            )
          ] });
        }
      },
      {
        id: "capacity",
        label: t("resources.resources.form.fields.capacity", "Capacity"),
        description: t(
          "resources.resources.form.fields.capacity.help",
          "Depends on the resource and can mean spots, units, quantity, or another type of capacity."
        ),
        type: "number"
      },
      {
        id: "capacityUnitValue",
        label: t("resources.resources.form.fields.capacityUnit", "Capacity unit"),
        type: "custom",
        component: ({ value, setValue }) => {
          if (!capacityUnitDictionaryId) {
            return /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("resources.resources.form.fields.capacityUnit.missing", "Capacity unit dictionary is not configured.") });
          }
          return /* @__PURE__ */ jsx(
            DictionarySelectControl,
            {
              dictionaryId: capacityUnitDictionaryId,
              value: typeof value === "string" ? value : null,
              onChange: (next) => setValue(next ?? ""),
              selectClassName: "w-full",
              seedOptions: selectedCapacityUnit ? [selectedCapacityUnit] : void 0
            }
          );
        }
      },
      {
        id: "appearance",
        label: t("resources.resources.form.appearance.label", "Appearance"),
        type: "custom",
        component: ({ value, setValue, disabled }) => {
          const appearance = value && typeof value === "object" ? value : {};
          return /* @__PURE__ */ jsx(
            AppearanceSelector,
            {
              icon: appearance.icon ?? null,
              color: appearance.color ?? null,
              onIconChange: (next) => setValue({ ...appearance, icon: next }),
              onColorChange: (next) => setValue({ ...appearance, color: next }),
              labels: appearanceLabels,
              disabled
            }
          );
        }
      }
    ];
    baseFields.push({
      id: "isActive",
      label: t("resources.resources.form.fields.active", "Active"),
      type: "checkbox"
    });
    return baseFields;
  }, [
    appearanceLabels,
    capacityUnitDictionaryId,
    resolveFieldsetCode,
    resourceTypes,
    selectedCapacityUnit,
    t
  ]);
  const groups = React.useMemo(() => {
    const baseGroups = [
      {
        id: "details",
        column: 1,
        fields: [
          "name",
          "description",
          "resourceTypeId",
          "capacity",
          "capacityUnitValue",
          "appearance",
          "isActive"
        ]
      },
      {
        id: "custom",
        title: t("entities.customFields.title", "Custom Attributes"),
        column: 2,
        kind: "customFields"
      }
    ];
    if (tagsSection) {
      baseGroups.push({
        id: "tags",
        column: 2,
        bare: true,
        component: () => /* @__PURE__ */ jsx(
          TagsSection,
          {
            title: tagsSection.title,
            tags: tagsSection.tags,
            onChange: tagsSection.onChange,
            loadOptions: tagsSection.loadOptions,
            createTag: tagsSection.createTag,
            onSave: tagsSection.onSave,
            labels: tagsSection.labels
          }
        )
      });
    }
    return baseGroups;
  }, [tagsSection, t]);
  return { fields, groups, resolveFieldsetCode, resourceTypesLoaded };
}
function ResourcesResourceForm(props) {
  const {
    title,
    submitLabel,
    backHref,
    cancelHref,
    embedded = false,
    successRedirect,
    initialValues,
    optimisticLockUpdatedAt,
    onSubmit,
    onDelete,
    isLoading,
    loadingMessage,
    formConfig
  } = props;
  const t = useT();
  const recordId = typeof initialValues?.id === "string" ? initialValues.id : null;
  const groups = React.useMemo(() => {
    const attachmentsGroup = {
      id: "attachments",
      title: t("attachments.library.title", "Attachments"),
      column: 1,
      component: () => /* @__PURE__ */ jsx(
        AttachmentsSection,
        {
          entityId: E.resources.resources_resource,
          recordId,
          showHeader: false
        }
      )
    };
    return [...formConfig.groups, attachmentsGroup];
  }, [formConfig.groups, recordId, t]);
  return /* @__PURE__ */ jsx(
    CrudForm,
    {
      embedded,
      title,
      backHref,
      versionHistory: recordId ? { resourceKind: "resources.resource", resourceId: recordId } : void 0,
      cancelHref,
      submitLabel,
      successRedirect,
      fields: formConfig.fields,
      groups,
      initialValues,
      optimisticLockUpdatedAt,
      entityId: E.resources.resources_resource,
      customFieldsetBindings: { [E.resources.resources_resource]: { valueKey: "customFieldsetCode" } },
      onSubmit,
      onDelete,
      isLoading,
      loadingMessage
    }
  );
}
export {
  ResourcesResourceForm,
  useResourcesResourceFormConfig
};
//# sourceMappingURL=ResourceCrudForm.js.map
