"use client";
import { jsx } from "react/jsx-runtime";
import * as React from "react";
import { parseChildEntity, getEntityApiPath } from "@nextsparkjs/registries/entity-registry.client";
function RelationDisplay({
  value,
  entityType,
  titleField,
  parentId,
  multiple = false,
  teamId
}) {
  const [titles, setTitles] = React.useState({});
  const [loading, setLoading] = React.useState(false);
  const ids = React.useMemo(() => {
    if (!value) return [];
    if (Array.isArray(value)) {
      return value.filter((id) => typeof id === "string" && id.trim() !== "");
    }
    if (typeof value === "string") {
      if (multiple && value.startsWith("[")) {
        try {
          const parsed = JSON.parse(value);
          return Array.isArray(parsed) ? parsed.filter((id) => typeof id === "string" && id.trim() !== "") : [];
        } catch {
          return value.trim() !== "" ? [value] : [];
        }
      }
      return value.trim() !== "" ? [value] : [];
    }
    return [];
  }, [value, multiple]);
  const loadedIdsRef = React.useRef([]);
  React.useEffect(() => {
    if (ids.length === 0) {
      setTitles({});
      loadedIdsRef.current = [];
      return;
    }
    const idsString = ids.sort().join(",");
    const loadedIdsString = loadedIdsRef.current.sort().join(",");
    if (idsString === loadedIdsString) {
      return;
    }
    const loadTitles = async () => {
      setLoading(true);
      try {
        let url;
        const childInfo = parseChildEntity(entityType);
        if (childInfo.isChild && childInfo.parentEntity && childInfo.childType && parentId) {
          const parentApiPath = getEntityApiPath(childInfo.parentEntity);
          if (parentApiPath) {
            url = new URL(`/api/v1/${parentApiPath}/${parentId}/child/${childInfo.childType}`, window.location.origin);
          } else {
            console.warn(`No API path found for parent entity: ${childInfo.parentEntity}`);
            setLoading(false);
            return;
          }
        } else {
          const apiPath = getEntityApiPath(entityType);
          const hasSpecificAPI = apiPath !== null;
          if (hasSpecificAPI) {
            url = new URL(`/api/v1/${apiPath}`, window.location.origin);
            url.searchParams.set("ids", ids.join(","));
            if (parentId) {
              url.searchParams.set("parentId", parentId);
            }
          } else {
            console.warn(`No specific API available for entity type: ${entityType}`);
            setLoading(false);
            return;
          }
        }
        const response = await fetch(url.toString(), {
          method: "GET",
          headers: {
            "Content-Type": "application/json",
            ...teamId && { "x-team-id": teamId }
          },
          credentials: "include"
        });
        if (response.ok) {
          const data = await response.json();
          if (data.success && Array.isArray(data.data)) {
            const newTitles = {};
            const filteredData = childInfo.isChild ? data.data.filter((item) => {
              const itemId = String(item.id || "");
              return ids.includes(itemId);
            }) : data.data;
            filteredData.forEach((item) => {
              const id = String(item.id || "");
              const title = String(item[titleField || "name"] || item.name || item.title || id);
              newTitles[id] = title;
            });
            setTitles(newTitles);
          }
          loadedIdsRef.current = [...ids];
        }
      } catch (error) {
        console.error(`Error loading titles for ${entityType}:`, error);
      } finally {
        setLoading(false);
      }
    };
    loadTitles();
  }, [ids, entityType, titleField, parentId, teamId]);
  if (ids.length === 0) {
    return /* @__PURE__ */ jsx("span", { children: "-" });
  }
  if (loading && Object.keys(titles).length === 0) {
    return /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "Cargando..." });
  }
  const displayValues = ids.map((id) => titles[id] || id);
  if (multiple) {
    return /* @__PURE__ */ jsx("span", { children: displayValues.join(", ") });
  }
  return /* @__PURE__ */ jsx("span", { children: displayValues[0] });
}
export {
  RelationDisplay
};
