"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { evaluateInjectedVisibility } from "./visibility-utils.js";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Input } from "../../primitives/input.js";
import { Checkbox } from "../../primitives/checkbox.js";
import { Textarea } from "../../primitives/textarea.js";
import { Label } from "../../primitives/label.js";
import { Spinner } from "../../primitives/spinner.js";
const MAX_CACHE_ENTRIES = 100;
const optionsCache = /* @__PURE__ */ new Map();
function evictExpiredCacheEntries() {
  if (optionsCache.size <= MAX_CACHE_ENTRIES) return;
  const now = Date.now();
  for (const [key, entry] of optionsCache) {
    if (entry.expiresAt < now) optionsCache.delete(key);
  }
}
function SelectField({
  field,
  value,
  onChange,
  disabled,
  options,
  optionsError,
  label
}) {
  const t = useT();
  return /* @__PURE__ */ jsxs("div", { className: "space-y-2", "data-crud-field-id": field.id, children: [
    /* @__PURE__ */ jsx(Label, { htmlFor: field.id, children: label }),
    /* @__PURE__ */ jsxs(
      "select",
      {
        id: field.id,
        className: "flex h-9 w-full rounded-md border border-input bg-background pl-3 pr-8 py-2 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
        value: typeof value === "string" ? value : "",
        disabled: disabled || options.length === 0 && !field.options?.length,
        onChange: (event) => onChange(field.id, event.target.value || void 0),
        children: [
          /* @__PURE__ */ jsx("option", { value: "", children: t("ui.filters.select.placeholder", "Select...") }),
          options.map((option) => /* @__PURE__ */ jsx("option", { value: option.value, children: option.labelKey ? t(option.labelKey, option.label) : option.label }, option.value))
        ]
      }
    ),
    optionsError ? /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground", children: t("ui.forms.optionsUnavailable", "Options unavailable") }) : null
  ] });
}
function InjectedField({ field, value, onChange, context, formData, readOnly = false }) {
  const t = useT();
  const [dynamicOptions, setDynamicOptions] = React.useState(null);
  const [optionsError, setOptionsError] = React.useState(false);
  React.useEffect(() => {
    let cancelled = false;
    const loadOptions = async () => {
      if (typeof field.optionsLoader !== "function") return;
      const ttl = Math.max(1, field.optionsCacheTtl ?? 60);
      const cacheKey = `${field.id}:${context.organizationId ?? ""}:${context.tenantId ?? ""}`;
      const cached = optionsCache.get(cacheKey);
      if (cached && cached.expiresAt > Date.now()) {
        setDynamicOptions(cached.options);
        return;
      }
      try {
        const loaded = await field.optionsLoader(context);
        if (cancelled) return;
        const normalized = Array.isArray(loaded) ? loaded : [];
        setDynamicOptions(normalized);
        setOptionsError(false);
        evictExpiredCacheEntries();
        optionsCache.set(cacheKey, { options: normalized, expiresAt: Date.now() + ttl * 1e3 });
      } catch {
        if (cancelled) return;
        setDynamicOptions(Array.isArray(field.options) ? field.options : null);
        setOptionsError(true);
      }
    };
    void loadOptions();
    return () => {
      cancelled = true;
    };
  }, [context, field.id, field.options, field.optionsCacheTtl, field.optionsLoader]);
  if (!evaluateInjectedVisibility(field.visibleWhen, formData, context)) return null;
  const label = field.labelKey ? t(field.labelKey, field.label) : t(field.label, field.label);
  const disabled = readOnly || field.readOnly;
  const options = dynamicOptions ?? field.options ?? [];
  if (field.type === "custom" && field.customComponent) {
    const CustomComponent = field.customComponent;
    return /* @__PURE__ */ jsx(React.Suspense, { fallback: /* @__PURE__ */ jsx(Spinner, { size: "sm" }), children: /* @__PURE__ */ jsx(
      CustomComponent,
      {
        value,
        onChange: (next) => onChange(field.id, next),
        context,
        disabled
      }
    ) });
  }
  if (field.type === "textarea") {
    return /* @__PURE__ */ jsxs("div", { className: "space-y-2", "data-crud-field-id": field.id, children: [
      /* @__PURE__ */ jsx(Label, { htmlFor: field.id, children: label }),
      /* @__PURE__ */ jsx(
        Textarea,
        {
          id: field.id,
          className: "min-h-[96px]",
          value: typeof value === "string" ? value : "",
          disabled,
          onChange: (event) => onChange(field.id, event.target.value)
        }
      )
    ] });
  }
  if (field.type === "select") {
    return /* @__PURE__ */ jsx(
      SelectField,
      {
        field,
        value,
        onChange,
        disabled,
        options,
        optionsError,
        label
      }
    );
  }
  if (field.type === "boolean") {
    return /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 text-sm", "data-crud-field-id": field.id, children: [
      /* @__PURE__ */ jsx(
        Checkbox,
        {
          checked: value === true,
          disabled,
          onCheckedChange: (checked) => onChange(field.id, checked === true)
        }
      ),
      /* @__PURE__ */ jsx("span", { children: label })
    ] });
  }
  return /* @__PURE__ */ jsxs("div", { className: "space-y-2", "data-crud-field-id": field.id, children: [
    /* @__PURE__ */ jsx(Label, { htmlFor: field.id, children: label }),
    /* @__PURE__ */ jsx(
      Input,
      {
        id: field.id,
        type: field.type === "number" ? "number" : field.type === "date" ? "date" : "text",
        value: typeof value === "string" || typeof value === "number" ? String(value) : "",
        disabled,
        onChange: (event) => {
          if (field.type === "number") {
            onChange(field.id, event.target.value === "" ? void 0 : Number(event.target.value));
            return;
          }
          onChange(field.id, event.target.value);
        }
      }
    )
  ] });
}
var InjectedField_default = InjectedField;
export {
  InjectedField,
  InjectedField_default as default
};
//# sourceMappingURL=InjectedField.js.map
