"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { FormHeader } from "@open-mercato/ui/backend/forms";
import { Button } from "@open-mercato/ui/primitives/button";
import { apiCallOrThrow, readApiResultOrThrow, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
import { collectCustomFieldValues } from "@open-mercato/ui/backend/utils/customFieldValues";
import { createCrudFormError } from "@open-mercato/ui/backend/utils/serverErrors";
import { updateCrud, deleteCrud } from "@open-mercato/ui/backend/utils/crud";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { ActivitiesSection, NotesSection, RecordNotFoundState } from "@open-mercato/ui/backend/detail";
import { buildRecordInjectionContext, useSetCurrentRecordInjectionContext } from "@open-mercato/ui/backend/injection/recordContext";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { VersionHistoryAction } from "@open-mercato/ui/backend/version-history";
import { SendObjectMessageDialog } from "@open-mercato/ui/backend/messages";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { extractCustomFieldEntries } from "@open-mercato/shared/lib/crud/custom-fields-client";
import { createTranslatorWithFallback } from "@open-mercato/shared/lib/i18n/translate";
import { buildResourceScheduleItems } from "@open-mercato/core/modules/resources/lib/resourceSchedule";
import { RESOURCES_RESOURCE_FIELDSET_DEFAULT } from "@open-mercato/core/modules/resources/lib/resourceCustomFields";
import { AvailabilityRulesEditor } from "@open-mercato/core/modules/planner/components/AvailabilityRulesEditor";
import { ResourcesResourceForm, useResourcesResourceFormConfig } from "@open-mercato/core/modules/resources/components/ResourceCrudForm";
import { renderDictionaryColor, renderDictionaryIcon, ICON_SUGGESTIONS } from "@open-mercato/core/modules/dictionaries/components/dictionaryAppearance";
import { createResourceNotesAdapter } from "@open-mercato/core/modules/resources/components/detail/notesAdapter";
import { createResourceActivitiesAdapter } from "@open-mercato/core/modules/resources/components/detail/activitiesAdapter";
import {
  createResourceDictionaryEntry,
  loadResourceDictionary
} from "@open-mercato/core/modules/resources/components/detail/dictionaries";
function normalizeResourceRecord(record) {
  return {
    ...record,
    resourceTypeId: record.resourceTypeId ?? record.resource_type_id ?? null,
    description: record.description ?? null,
    capacityUnitValue: record.capacityUnitValue ?? record.capacity_unit_value ?? null,
    capacityUnitName: record.capacityUnitName ?? record.capacity_unit_name ?? null,
    capacityUnitColor: record.capacityUnitColor ?? record.capacity_unit_color ?? null,
    capacityUnitIcon: record.capacityUnitIcon ?? record.capacity_unit_icon ?? null,
    appearanceIcon: record.appearanceIcon ?? record.appearance_icon ?? null,
    appearanceColor: record.appearanceColor ?? record.appearance_color ?? null,
    isActive: record.isActive ?? record.is_active ?? true
  };
}
function ResourcesResourceDetailPage({ params }) {
  const resourceId = params?.id;
  const t = useT();
  const detailTranslator = React.useMemo(() => createTranslatorWithFallback(t), [t]);
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const [initialValues, setInitialValues] = React.useState(null);
  const [isNotFound, setIsNotFound] = React.useState(false);
  const loadedResourceIdRef = React.useRef(null);
  const [tags, setTags] = React.useState([]);
  const [activeTab, setActiveTab] = React.useState("details");
  const [activeDetailTab, setActiveDetailTab] = React.useState("notes");
  const [sectionAction, setSectionAction] = React.useState(null);
  const [availabilityRuleSetId, setAvailabilityRuleSetId] = React.useState(null);
  const [selectedCapacityUnit, setSelectedCapacityUnit] = React.useState(null);
  const [activityDictionaryId, setActivityDictionaryId] = React.useState(null);
  const [activityTypeEntries, setActivityTypeEntries] = React.useState([]);
  const flashShownRef = React.useRef(false);
  const availabilityMode = "availability";
  const mutationContextId = React.useMemo(
    () => resourceId ? `resources.resource:${resourceId}` : "resources.resource:pending",
    [resourceId]
  );
  const { runMutation, retryLastMutation } = useGuardedMutation({
    contextId: mutationContextId,
    blockedMessage: t("ui.forms.flash.saveBlocked", "Save blocked by validation")
  });
  const mutationContext = React.useMemo(
    () => ({
      formId: mutationContextId,
      resourceKind: "resources.resource",
      resourceId,
      data: initialValues,
      retryLastMutation
    }),
    [initialValues, mutationContextId, resourceId, retryLastMutation]
  );
  const runMutationWithContext = React.useCallback(
    async (operation, mutationPayload) => runMutation({
      operation,
      mutationPayload,
      context: mutationContext
    }),
    [mutationContext, runMutation]
  );
  const notesAdapter = React.useMemo(
    () => createResourceNotesAdapter(detailTranslator, { runMutation: runMutationWithContext }),
    [detailTranslator, runMutationWithContext]
  );
  const activitiesAdapter = React.useMemo(
    () => createResourceActivitiesAdapter(detailTranslator, { runMutation: runMutationWithContext }),
    [detailTranslator, runMutationWithContext]
  );
  const activityTypeLabels = React.useMemo(() => ({
    placeholder: t("resources.resources.detail.activities.dictionary.placeholder", "Select an activity type"),
    addLabel: t("resources.resources.detail.activities.dictionary.add", "Add type"),
    addPrompt: t("resources.resources.detail.activities.dictionary.prompt", "Name the type"),
    dialogTitle: t("resources.resources.detail.activities.dictionary.dialogTitle", "Add activity type"),
    valueLabel: t("resources.resources.detail.activities.dictionary.valueLabel", "Name"),
    valuePlaceholder: t("resources.resources.detail.activities.dictionary.valuePlaceholder", "Name"),
    labelLabel: t("resources.resources.detail.activities.dictionary.labelLabel", "Label"),
    labelPlaceholder: t("resources.resources.detail.activities.dictionary.labelPlaceholder", "Display name shown in UI"),
    emptyError: t("resources.resources.detail.activities.dictionary.emptyError", "Please enter a name"),
    cancelLabel: t("resources.resources.detail.activities.dictionary.cancel", "Cancel"),
    saveLabel: t("resources.resources.detail.activities.dictionary.save", "Save"),
    saveShortcutHint: t("resources.resources.detail.activities.dictionary.saveShortcut", "\u2318/Ctrl + Enter"),
    errorLoad: t("resources.resources.detail.activities.dictionary.errorLoad", "Failed to load options"),
    errorSave: t("resources.resources.detail.activities.dictionary.errorSave", "Failed to save option"),
    loadingLabel: t("resources.resources.detail.activities.dictionary.loading", "Loading\u2026"),
    manageTitle: t("resources.resources.detail.activities.dictionary.manage", "Manage dictionary")
  }), [t]);
  const loadActivityOptions = React.useCallback(async () => {
    const { dictionary, entries } = await loadResourceDictionary("activityTypes");
    setActivityDictionaryId(dictionary?.id ?? null);
    setActivityTypeEntries(entries);
    return entries;
  }, []);
  const createActivityOption = React.useCallback(
    async (input) => {
      const entry = await createResourceDictionaryEntry("activityTypes", input);
      if (!entry) {
        throw new Error(t("resources.resources.detail.activities.dictionary.errorSave", "Failed to save option"));
      }
      return entry;
    },
    [t]
  );
  React.useEffect(() => {
    loadActivityOptions().catch(() => {
    });
  }, [loadActivityOptions]);
  const activityTypeMap = React.useMemo(
    () => new Map(activityTypeEntries.map((entry) => [entry.value, entry])),
    [activityTypeEntries]
  );
  const resolveActivityPresentation = React.useCallback(
    (activity) => {
      const entry = activityTypeMap.get(activity.activityType);
      return {
        label: entry?.label ?? activity.activityType,
        icon: entry?.icon ?? activity.appearanceIcon ?? null,
        color: entry?.color ?? activity.appearanceColor ?? null
      };
    },
    [activityTypeMap]
  );
  const manageActivityHref = React.useMemo(() => {
    if (!activityDictionaryId) return "/backend/config/dictionaries";
    return `/backend/config/dictionaries?dictionaryId=${encodeURIComponent(activityDictionaryId)}`;
  }, [activityDictionaryId]);
  const appearanceLabels = React.useMemo(() => ({
    colorLabel: t("resources.resources.detail.activities.appearance.colorLabel", "Color"),
    colorHelp: t("resources.resources.detail.activities.appearance.colorHelp", "Pick a highlight color for this entry."),
    colorClearLabel: t("resources.resources.detail.activities.appearance.colorClear", "Remove color"),
    iconLabel: t("resources.resources.detail.activities.appearance.iconLabel", "Icon or emoji"),
    iconPlaceholder: t("resources.resources.detail.activities.appearance.iconPlaceholder", "Type an emoji or pick one of the suggestions."),
    iconPickerTriggerLabel: t("resources.resources.detail.activities.appearance.iconBrowse", "Browse icons and emojis"),
    iconSearchPlaceholder: t("resources.resources.detail.activities.appearance.iconSearchPlaceholder", "Search icons or emojis\u2026"),
    iconSearchEmptyLabel: t("resources.resources.detail.activities.appearance.iconSearchEmpty", "No icons match your search."),
    iconSuggestionsLabel: t("resources.resources.detail.activities.appearance.iconSuggestions", "Suggestions"),
    iconClearLabel: t("resources.resources.detail.activities.appearance.iconClear", "Remove icon"),
    previewEmptyLabel: t("resources.resources.detail.activities.appearance.previewEmpty", "No appearance selected")
  }), [t]);
  const renderCustomFields = React.useCallback((activity) => {
    const entries = Array.isArray(activity.customFields) ? activity.customFields : [];
    if (!entries.length) return null;
    const emptyLabel = t("resources.resources.detail.activities.customFields.empty", "Not provided");
    return /* @__PURE__ */ jsx("div", { className: "grid gap-3 sm:grid-cols-2", children: entries.map((entry, index) => {
      const label = entry.label ?? entry.key;
      const value = entry.value;
      const hasValue = !(value == null || value === "" || Array.isArray(value) && value.length === 0);
      const content = hasValue ? Array.isArray(value) ? value.map((item) => String(item)).join(", ") : String(value) : emptyLabel;
      return /* @__PURE__ */ jsxs(
        "div",
        {
          className: "rounded-md border border-border/70 bg-muted/30 px-3 py-2",
          children: [
            /* @__PURE__ */ jsx("div", { className: "text-xs font-medium text-muted-foreground", children: label }),
            /* @__PURE__ */ jsx("div", { className: "mt-1 text-sm text-foreground", children: content })
          ]
        },
        `activity-${activity.id ?? "row"}-custom-${index}`
      );
    }) });
  }, [t]);
  React.useEffect(() => {
    if (!searchParams) return;
    const tabParam = searchParams.get("tab");
    if (tabParam === "availability") {
      setActiveTab("availability");
    }
    const created = searchParams.get("created") === "1";
    if (created && !flashShownRef.current) {
      flashShownRef.current = true;
      flash(t("resources.resources.flash.createdAvailability", "Saved. You can now set availability."), "success");
      const nextParams = new URLSearchParams(searchParams.toString());
      nextParams.delete("created");
      const nextQuery = nextParams.toString();
      const nextPath = resourceId ? `/backend/resources/resources/${encodeURIComponent(resourceId)}${nextQuery ? `?${nextQuery}` : ""}` : `/backend/resources/resources${nextQuery ? `?${nextQuery}` : ""}`;
      router.replace(nextPath);
    }
  }, [resourceId, router, searchParams, t]);
  const buildScheduleItems = React.useCallback(
    ({ availabilityRules, translate }) => buildResourceScheduleItems({
      availabilityRules,
      isAvailableByDefault: false,
      translate
    }),
    []
  );
  const tagLabels = React.useMemo(
    () => ({
      loading: t("resources.resources.tags.loading", "Loading tags..."),
      placeholder: t("resources.resources.tags.placeholder", "Type to add tags"),
      empty: t("resources.resources.tags.placeholder", "No tags yet. Add labels to keep resources organized."),
      loadError: t("resources.resources.tags.loadError", "Failed to load tags."),
      createError: t("resources.resources.tags.createError", "Failed to create tag."),
      updateError: t("resources.resources.tags.updateError", "Failed to update tags."),
      labelRequired: t("resources.resources.tags.labelRequired", "Tag name is required."),
      saveShortcut: t("resources.resources.tags.saveShortcut", "Save Cmd+Enter / Ctrl+Enter"),
      cancelShortcut: t("resources.resources.tags.cancelShortcut", "Cancel (Esc)"),
      edit: t("ui.forms.actions.edit", "Edit"),
      cancel: t("ui.forms.actions.cancel", "Cancel"),
      success: t("resources.resources.tags.success", "Tags updated.")
    }),
    [t]
  );
  const handleSubmit = React.useCallback(async (values) => {
    if (!resourceId) return;
    const appearance = values.appearance && typeof values.appearance === "object" ? values.appearance : {};
    const { appearance: _appearance, ...rest } = values;
    const customFieldsetCode = typeof values.customFieldsetCode === "string" && values.customFieldsetCode.trim().length ? values.customFieldsetCode.trim() : RESOURCES_RESOURCE_FIELDSET_DEFAULT;
    const payload = {
      ...rest,
      id: resourceId,
      resourceTypeId: values.resourceTypeId || null,
      capacity: values.capacity ? Number(values.capacity) : null,
      capacityUnitValue: values.capacityUnitValue ? String(values.capacityUnitValue) : null,
      appearanceIcon: appearance.icon ?? null,
      appearanceColor: appearance.color ?? null,
      isActive: values.isActive ?? true,
      customFieldsetCode,
      ...collectCustomFieldValues(values)
    };
    if (!payload.name || String(payload.name).trim().length === 0) {
      throw createCrudFormError(t("resources.resources.form.errors.nameRequired", "Name is required."));
    }
    await updateCrud("resources/resources", payload, {
      errorMessage: t("resources.resources.form.errors.update", "Failed to update resource.")
    });
    flash(t("resources.resources.form.flash.updated", "Resource updated."), "success");
  }, [resourceId, t]);
  const tabs = React.useMemo(() => [
    { id: "details", label: t("resources.resources.tabs.details", "Details") },
    { id: "availability", label: t("resources.resources.tabs.availability", "Availability") }
  ], [t]);
  const detailTabs = React.useMemo(() => [
    { id: "notes", label: t("resources.resources.detail.tabs.notes", "Notes") },
    { id: "activities", label: t("resources.resources.detail.tabs.activities", "Activities") }
  ], [t]);
  const loadTagOptions = React.useCallback(
    async (query) => {
      const params2 = new URLSearchParams({ pageSize: "100" });
      if (query) params2.set("search", query);
      const payload = await readApiResultOrThrow(
        `/api/resources/tags?${params2.toString()}`,
        void 0,
        { errorMessage: t("resources.resources.tags.loadError", "Failed to load tags.") }
      );
      const items = Array.isArray(payload?.items) ? payload.items : [];
      return items.map((item) => {
        if (!item || typeof item !== "object") return null;
        const raw = item;
        const rawId = typeof raw.id === "string" ? raw.id : typeof raw.tagId === "string" ? raw.tagId : null;
        if (!rawId) return null;
        const labelValue = typeof raw.label === "string" && raw.label.trim().length && raw.label.trim() || typeof raw.slug === "string" && raw.slug.trim().length && raw.slug.trim() || rawId;
        const color = typeof raw.color === "string" && raw.color.trim().length ? raw.color.trim() : null;
        return { id: rawId, label: labelValue, color };
      }).filter((entry) => entry !== null);
    },
    [t]
  );
  const createTag = React.useCallback(
    async (label) => {
      const trimmed = label.trim();
      if (!trimmed.length) {
        throw new Error(t("resources.resources.tags.labelRequired", "Tag name is required."));
      }
      const requestBody = { label: trimmed };
      const response = await runMutationWithContext(
        () => apiCallOrThrow(
          "/api/resources/tags",
          {
            method: "POST",
            headers: { "content-type": "application/json" },
            body: JSON.stringify(requestBody)
          },
          { errorMessage: t("resources.resources.tags.createError", "Failed to create tag.") }
        ),
        { operation: "createTag", label: trimmed }
      );
      const payload = response.result ?? {};
      const id = typeof payload?.id === "string" ? payload.id : typeof payload?.tagId === "string" ? payload.tagId : "";
      if (!id) throw new Error(t("resources.resources.tags.createError", "Failed to create tag."));
      const color = typeof payload?.color === "string" && payload.color.trim().length ? payload.color.trim() : null;
      return { id, label: trimmed, color };
    },
    [runMutationWithContext, t]
  );
  const assignTag = React.useCallback(async (tagId) => {
    if (!resourceId) return;
    const requestBody = { tagId, resourceId };
    await runMutationWithContext(
      () => apiCallOrThrow(
        "/api/resources/resources/tags/assign",
        {
          method: "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify(requestBody)
        },
        { errorMessage: t("resources.resources.tags.updateError", "Failed to update tags.") }
      ),
      { operation: "assignTag", resourceId, tagId }
    );
  }, [resourceId, runMutationWithContext, t]);
  const unassignTag = React.useCallback(async (tagId) => {
    if (!resourceId) return;
    const requestBody = { tagId, resourceId };
    await runMutationWithContext(
      () => apiCallOrThrow(
        "/api/resources/resources/tags/unassign",
        {
          method: "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify(requestBody)
        },
        { errorMessage: t("resources.resources.tags.updateError", "Failed to update tags.") }
      ),
      { operation: "unassignTag", resourceId, tagId }
    );
  }, [resourceId, runMutationWithContext, t]);
  const handleTagsSave = React.useCallback(
    async ({ next, added, removed }) => {
      if (!resourceId) return;
      await Promise.all([
        ...added.map((tag) => assignTag(tag.id)),
        ...removed.map((tag) => unassignTag(tag.id))
      ]);
      setTags(next);
      flash(t("resources.resources.tags.success", "Tags updated."), "success");
    },
    [assignTag, resourceId, t, unassignTag]
  );
  const tagsSection = React.useMemo(
    () => ({
      title: t("resources.resources.tags.title", "Tags"),
      tags,
      onChange: setTags,
      loadOptions: loadTagOptions,
      createTag,
      onSave: handleTagsSave,
      labels: tagLabels
    }),
    [createTag, handleTagsSave, loadTagOptions, t, tagLabels, tags]
  );
  const formConfig = useResourcesResourceFormConfig({
    tagsSection,
    selectedResourceTypeId: typeof initialValues?.resourceTypeId === "string" ? initialValues.resourceTypeId : null,
    selectedCapacityUnit: typeof initialValues?.capacityUnitValue === "string" && initialValues.capacityUnitValue.length > 0 ? selectedCapacityUnit : null
  });
  const { resourceTypesLoaded, resolveFieldsetCode } = formConfig;
  React.useEffect(() => {
    if (!resourceId || !resourceTypesLoaded) return;
    if (loadedResourceIdRef.current === resourceId) return;
    setIsNotFound(false);
    let cancelled = false;
    async function loadResource() {
      try {
        const params2 = new URLSearchParams();
        params2.set("page", "1");
        params2.set("pageSize", "1");
        if (resourceId) params2.set("ids", resourceId);
        const record = await readApiResultOrThrow(`/api/resources/resources?${params2.toString()}`);
        const resourceRaw = Array.isArray(record?.items) ? record.items[0] : null;
        const resource = resourceRaw ? normalizeResourceRecord(resourceRaw) : null;
        if (!resource) {
          if (!cancelled) setIsNotFound(true);
          return;
        }
        if (!cancelled) {
          loadedResourceIdRef.current = resourceId ?? null;
          const customValues = extractCustomFieldEntries(resource);
          setTags(Array.isArray(resource.tags) ? resource.tags : []);
          setAvailabilityRuleSetId(
            typeof resource.availabilityRuleSetId === "string" ? resource.availabilityRuleSetId : typeof resource.availability_rule_set_id === "string" ? resource.availability_rule_set_id : null
          );
          setSelectedCapacityUnit(
            typeof resource.capacityUnitValue === "string" && resource.capacityUnitValue.length > 0 ? {
              value: resource.capacityUnitValue,
              label: typeof resource.capacityUnitName === "string" && resource.capacityUnitName.length > 0 ? resource.capacityUnitName : resource.capacityUnitValue,
              color: typeof resource.capacityUnitColor === "string" ? resource.capacityUnitColor : null,
              icon: typeof resource.capacityUnitIcon === "string" ? resource.capacityUnitIcon : null
            } : null
          );
          setInitialValues({
            id: resource.id,
            name: resource.name,
            description: resource.description ?? "",
            resourceTypeId: resource.resourceTypeId || "",
            capacity: resource.capacity ?? "",
            capacityUnitValue: resource.capacityUnitValue ?? "",
            appearance: { icon: resource.appearanceIcon ?? null, color: resource.appearanceColor ?? null },
            isActive: resource.isActive ?? true,
            updatedAt: typeof resource.updatedAt === "string" ? resource.updatedAt : typeof resource.updated_at === "string" ? resource.updated_at : null,
            customFieldsetCode: resource.resourceTypeId ? resolveFieldsetCode(resource.resourceTypeId) : RESOURCES_RESOURCE_FIELDSET_DEFAULT,
            ...customValues
          });
        }
      } catch (error) {
        const message = error instanceof Error ? error.message : t("resources.resources.form.errors.load", "Failed to load resource.");
        flash(message, "error");
      }
    }
    loadResource();
    return () => {
      cancelled = true;
    };
  }, [resourceId, resourceTypesLoaded, resolveFieldsetCode, t]);
  const handleDelete = React.useCallback(async () => {
    if (!resourceId) return;
    const resourceOptimisticLockHeader = buildOptimisticLockHeader(
      typeof initialValues?.updatedAt === "string" ? initialValues.updatedAt : null
    );
    const deleteResource = () => deleteCrud("resources/resources", resourceId, {
      errorMessage: t("resources.resources.form.errors.delete", "Failed to delete resource.")
    });
    await runMutationWithContext(
      () => Object.keys(resourceOptimisticLockHeader).length > 0 ? withScopedApiRequestHeaders(resourceOptimisticLockHeader, deleteResource) : deleteResource(),
      { operation: "deleteResource", id: resourceId, updatedAt: initialValues?.updatedAt ?? null }
    );
    flash(t("resources.resources.form.flash.deleted", "Resource deleted."), "success");
    router.push("/backend/resources/resources");
  }, [initialValues?.updatedAt, resourceId, router, runMutationWithContext, t]);
  const handleRulesetChange = React.useCallback(async (nextId) => {
    if (!resourceId) return;
    const updateSchedule = () => updateCrud("resources/resources", { id: resourceId, availabilityRuleSetId: nextId }, {
      errorMessage: t("resources.resources.availability.ruleset.updateError", "Failed to update schedule.")
    });
    const resourceOptimisticLockHeader = buildOptimisticLockHeader(
      typeof initialValues?.updatedAt === "string" ? initialValues.updatedAt : null
    );
    await runMutationWithContext(
      () => Object.keys(resourceOptimisticLockHeader).length > 0 ? withScopedApiRequestHeaders(resourceOptimisticLockHeader, updateSchedule) : updateSchedule(),
      { operation: "updateAvailabilityRuleSet", id: resourceId, availabilityRuleSetId: nextId }
    );
    setAvailabilityRuleSetId(nextId);
    flash(t("resources.resources.availability.ruleset.updateSuccess", "Schedule updated."), "success");
  }, [initialValues?.updatedAt, resourceId, runMutationWithContext, t]);
  const resourceTitle = typeof initialValues?.name === "string" && initialValues.name.trim().length > 0 ? initialValues.name.trim() : t("resources.resources.detail.untitled", "Unnamed resource");
  useSetCurrentRecordInjectionContext(
    buildRecordInjectionContext({
      resourceKind: "resources.resource",
      resourceId: resourceId || null,
      updatedAt: typeof initialValues?.updatedAt === "string" ? initialValues.updatedAt : null,
      data: initialValues,
      path: pathname
    })
  );
  if (isNotFound) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      RecordNotFoundState,
      {
        label: t("resources.resources.form.errors.notFound", "Resource not found."),
        backHref: "/backend/resources/resources",
        backLabel: t("resources.resources.detail.back", "Back to resources")
      }
    ) }) });
  }
  return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
    /* @__PURE__ */ jsx(
      FormHeader,
      {
        mode: "detail",
        backHref: "/backend/resources/resources",
        backLabel: t("resources.resources.detail.back", "Back to resources"),
        utilityActions: /* @__PURE__ */ jsxs(Fragment, { children: [
          resourceId ? /* @__PURE__ */ jsx(
            SendObjectMessageDialog,
            {
              object: {
                entityModule: "resources",
                entityType: "resource",
                entityId: resourceId,
                previewData: {
                  title: resourceTitle
                }
              },
              viewHref: `/backend/resources/resources/${resourceId}`
            }
          ) : null,
          /* @__PURE__ */ jsx(
            VersionHistoryAction,
            {
              config: resourceId ? { resourceKind: "resources.resource", resourceId, includeRelated: true } : null,
              t
            }
          )
        ] }),
        title: resourceTitle,
        subtitle: t("resources.resources.detail.subtitle", "Resource profile and activity")
      }
    ),
    /* @__PURE__ */ jsx("div", { className: "border-b", children: /* @__PURE__ */ jsx("nav", { className: "flex flex-wrap items-center gap-5 text-sm", "aria-label": t("resources.resources.tabs.label", "Resource sections"), children: tabs.map((tab) => /* @__PURE__ */ jsx(
      Button,
      {
        type: "button",
        role: "tab",
        "aria-selected": activeTab === tab.id,
        variant: "ghost",
        size: "sm",
        className: `relative -mb-px h-auto rounded-none border-b-2 px-0 py-2 font-medium ${activeTab === tab.id ? "border-accent-indigo text-foreground" : "border-transparent text-muted-foreground hover:text-foreground"}`,
        onClick: () => setActiveTab(tab.id),
        children: tab.label
      },
      tab.id
    )) }) }),
    activeTab === "details" ? /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card p-4", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center justify-between gap-3", children: [
          /* @__PURE__ */ jsx("div", { className: "flex gap-2", children: detailTabs.map((tab) => /* @__PURE__ */ jsx(
            Button,
            {
              type: "button",
              variant: "ghost",
              size: "sm",
              className: `relative -mb-px h-auto rounded-none border-b-2 px-0 py-1 font-medium ${activeDetailTab === tab.id ? "border-accent-indigo text-foreground" : "border-transparent text-muted-foreground hover:text-foreground"}`,
              onClick: () => setActiveDetailTab(tab.id),
              children: tab.label
            },
            tab.id
          )) }),
          sectionAction ? /* @__PURE__ */ jsxs(
            Button,
            {
              type: "button",
              size: "sm",
              disabled: sectionAction.disabled,
              onClick: () => sectionAction.onClick(),
              children: [
                sectionAction.icon ?? null,
                sectionAction.label
              ]
            }
          ) : null
        ] }),
        activeDetailTab === "notes" ? /* @__PURE__ */ jsx(
          NotesSection,
          {
            entityId: resourceId ?? null,
            emptyLabel: t("resources.resources.detail.notes.empty", "No notes yet."),
            viewerUserId: null,
            viewerName: null,
            viewerEmail: null,
            addActionLabel: t("resources.resources.detail.notes.add", "Add note"),
            emptyState: {
              title: t("resources.resources.detail.notes.emptyTitle", "Keep everyone in the loop"),
              actionLabel: t("resources.resources.detail.notes.emptyAction", "Add a note")
            },
            onActionChange: setSectionAction,
            translator: detailTranslator,
            labelPrefix: "resources.resources.detail.notes",
            inlineLabelPrefix: "resources.resources.detail.inline",
            dataAdapter: notesAdapter,
            renderIcon: renderDictionaryIcon,
            renderColor: renderDictionaryColor,
            iconSuggestions: ICON_SUGGESTIONS
          }
        ) : null,
        activeDetailTab === "activities" ? /* @__PURE__ */ jsx(
          ActivitiesSection,
          {
            entityId: resourceId ?? null,
            addActionLabel: t("resources.resources.detail.activities.add", "Log activity"),
            emptyState: {
              title: t("resources.resources.detail.activities.emptyTitle", "No activities yet"),
              actionLabel: t("resources.resources.detail.activities.emptyAction", "Add an activity")
            },
            onActionChange: setSectionAction,
            dataAdapter: activitiesAdapter,
            activityTypeLabels,
            loadActivityOptions,
            createActivityOption,
            resolveActivityPresentation,
            renderCustomFields,
            labelPrefix: "resources.resources.detail.activities",
            renderIcon: renderDictionaryIcon,
            renderColor: renderDictionaryColor,
            appearanceLabels,
            manageHref: manageActivityHref,
            customFieldEntityIds: ["resources:resources_resource_activity"]
          }
        ) : null
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card p-4", children: [
        /* @__PURE__ */ jsx("h2", { className: "mb-4 text-sm font-semibold uppercase text-muted-foreground", children: t("resources.resources.detail.formTitle", "Resource settings") }),
        /* @__PURE__ */ jsx(
          ResourcesResourceForm,
          {
            embedded: true,
            title: t("resources.resources.form.editTitle", "Edit resource"),
            backHref: "/backend/resources/resources",
            cancelHref: "/backend/resources/resources",
            successRedirect: "/backend/resources/resources",
            formConfig,
            initialValues: initialValues ?? void 0,
            optimisticLockUpdatedAt: typeof initialValues?.updatedAt === "string" ? initialValues.updatedAt : null,
            onSubmit: handleSubmit,
            onDelete: handleDelete,
            isLoading: !initialValues,
            loadingMessage: t("resources.resources.form.loading", "Loading resource...")
          }
        )
      ] })
    ] }) : /* @__PURE__ */ jsx(
      AvailabilityRulesEditor,
      {
        subjectType: "resource",
        subjectId: resourceId ?? "",
        labelPrefix: "resources.resources",
        mode: availabilityMode,
        rulesetId: availabilityRuleSetId,
        onRulesetChange: handleRulesetChange,
        buildScheduleItems
      }
    )
  ] }) }) });
}
export {
  ResourcesResourceDetailPage as default
};
//# sourceMappingURL=page.js.map
