"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { useState } from "react";
import { Card, CardContent } from "../ui/card";
import { Alert, AlertDescription } from "../ui/alert";
import { AlertCircle, Loader2 } from "lucide-react";
import { getEntity, ENTITY_REGISTRY } from "../../lib/entities/queries";
import { EntityFieldRenderer } from "./EntityFieldRenderer";
import { EntityChildManager } from "./EntityChildManager";
import { EntityDetailHeader } from "./EntityDetailHeader";
import { createTestId, createCyId } from "../../lib/test";
import { useTeam } from "../../hooks/useTeam";
import { usePermissions } from "../../lib/permissions/hooks";
function generateTestIds(entityName) {
  return {
    container: createTestId(entityName, "detail"),
    backButton: createTestId(entityName, "back"),
    editButton: createTestId(entityName, "edit"),
    deleteButton: createTestId(entityName, "delete"),
    actionsMenu: createTestId(entityName, "actions"),
    childSection: (childName) => createTestId(entityName, "child", childName)
  };
}
function EntityDetail({
  entityConfig,
  data,
  isLoading = false,
  error = null,
  childData = {},
  childEntityNames = [],
  onEdit,
  onDelete,
  onChildAdd,
  onChildEdit,
  onChildDelete,
  onRefresh,
  enableActions = true,
  className,
  customFormComponents = {},
  customSections = []
}) {
  const [isDeleting, setIsDeleting] = useState(false);
  const { teamId } = useTeam();
  const { canUpdate, canDelete } = usePermissions({
    canUpdate: `${entityConfig.slug}.update`,
    canDelete: `${entityConfig.slug}.delete`
  });
  const testIds = generateTestIds(entityConfig.slug);
  const detailFields = entityConfig.fields.filter((field) => field.display.showInDetail).sort((a, b) => a.display.order - b.display.order);
  console.log("[EntityDetail] childEntityNames:", childEntityNames);
  console.log("[EntityDetail] childData:", childData);
  console.log("[EntityDetail] Object.keys(childData):", Object.keys(childData));
  console.log("[EntityDetail] customFormComponents:", customFormComponents);
  console.log("[EntityDetail] customFormComponents keys:", Object.keys(customFormComponents || {}));
  const childEntities = childEntityNames || [];
  console.log("[EntityDetail] childEntities (always show if names provided):", childEntities);
  const handleDelete = async () => {
    if (!onDelete) return;
    setIsDeleting(true);
    try {
      await onDelete();
    } catch (error2) {
      console.error("Delete failed:", error2);
    } finally {
      setIsDeleting(false);
    }
  };
  if (isLoading) {
    return /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center p-8", children: /* @__PURE__ */ jsx(Loader2, { className: "h-8 w-8 animate-spin text-muted-foreground" }) });
  }
  if (error) {
    return /* @__PURE__ */ jsxs(Alert, { variant: "destructive", children: [
      /* @__PURE__ */ jsx(AlertCircle, { className: "h-4 w-4" }),
      /* @__PURE__ */ jsx(AlertDescription, { children: error })
    ] });
  }
  return /* @__PURE__ */ jsx("div", { className: "p-6", children: /* @__PURE__ */ jsxs(
    "div",
    {
      className: `max-w-7xl mx-auto space-y-6 ${className || ""}`,
      "data-testid": testIds.container,
      "data-cy": createCyId(entityConfig.slug, "detail"),
      children: [
        enableActions ? /* @__PURE__ */ jsx(
          EntityDetailHeader,
          {
            entityConfig,
            mode: "view",
            entity: {
              id: String(data.id),
              createdAt: data.createdAt,
              updatedAt: data.updatedAt,
              ...data
            },
            onEdit,
            onDelete: onDelete ? handleDelete : void 0,
            canEdit: canUpdate,
            canDelete,
            isDeleting
          }
        ) : /* @__PURE__ */ jsx(
          EntityDetailHeader,
          {
            entityConfig,
            mode: "view",
            entity: {
              id: String(data.id),
              createdAt: data.createdAt,
              updatedAt: data.updatedAt,
              ...data
            },
            canEdit: false,
            canDelete: false
          }
        ),
        /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
          /* @__PURE__ */ jsx(Card, { children: /* @__PURE__ */ jsx(CardContent, { className: "pt-6 space-y-6", children: /* @__PURE__ */ jsx("div", { className: "grid grid-cols-1 md:grid-cols-12 gap-6", children: detailFields.map((field) => {
            const getColumnSpanClass = (width) => {
              if (!width) return "md:col-span-6";
              switch (width) {
                case 1:
                  return "md:col-span-1";
                case 2:
                  return "md:col-span-2";
                case 3:
                  return "md:col-span-3";
                case 4:
                  return "md:col-span-4";
                case 5:
                  return "md:col-span-5";
                case 6:
                  return "md:col-span-6";
                case 7:
                  return "md:col-span-7";
                case 8:
                  return "md:col-span-8";
                case 9:
                  return "md:col-span-9";
                case 10:
                  return "md:col-span-10";
                case 11:
                  return "md:col-span-11";
                case 12:
                  return "md:col-span-12";
                default:
                  return "md:col-span-12";
              }
            };
            return /* @__PURE__ */ jsx(
              "div",
              {
                className: getColumnSpanClass(field.display.columnWidth),
                children: /* @__PURE__ */ jsx(
                  EntityFieldRenderer,
                  {
                    field,
                    value: data[field.name],
                    mode: "display",
                    context: {
                      entityType: entityConfig.slug,
                      formData: data,
                      // Pass the record data so RelationDisplay can access parentId
                      teamId
                      // Pass teamId for user field display
                    }
                  }
                )
              },
              field.name
            );
          }) }) }) }),
          customSections.filter((section) => section.position === "after-details").map((section) => /* @__PURE__ */ jsx(
            section.component,
            {
              data,
              entityConfig
            },
            section.id
          )),
          childEntities.map((childName) => {
            var _a, _b, _c, _d;
            const childEntityConfig = getEntity(childName);
            const childRegistryEntry = ENTITY_REGISTRY[childName];
            if (!childEntityConfig || !childRegistryEntry) {
              console.warn(`Child entity "${childName}" not found in registry`);
              return null;
            }
            const childConfig = {
              fields: childEntityConfig.fields,
              display: {
                title: ((_a = childEntityConfig.names) == null ? void 0 : _a.plural) || ((_b = childEntityConfig.display) == null ? void 0 : _b.title) || childName,
                description: `Manage ${(((_c = childEntityConfig.names) == null ? void 0 : _c.plural) || ((_d = childEntityConfig.display) == null ? void 0 : _d.title) || childName).toLowerCase()} for this ${entityConfig.names.singular.toLowerCase()}`,
                mode: "table"
              }
            };
            console.log(`[EntityDetail] Rendering EntityChildManager for ${childName}`);
            console.log(`[EntityDetail] customFormComponents[${childName}]:`, customFormComponents[childName]);
            return /* @__PURE__ */ jsx(
              EntityChildManager,
              {
                parentEntityConfig: entityConfig,
                parentEntityId: String(data.id),
                childEntityName: childName,
                childEntityConfig: childConfig,
                childData: childData[childName] || [],
                onChildAdd: onChildAdd ? (data2) => onChildAdd(childName, data2) : void 0,
                onChildUpdate: onChildEdit ? (id, data2) => onChildEdit(childName, id, data2) : void 0,
                onChildDelete: onChildDelete ? (id) => onChildDelete(childName, id) : void 0,
                onRefresh,
                isLoading,
                customFormComponent: customFormComponents[childName]
              },
              childName
            );
          }),
          customSections.filter((section) => !section.position || section.position === "after-children").map((section) => /* @__PURE__ */ jsx(
            section.component,
            {
              data,
              entityConfig
            },
            section.id
          ))
        ] })
      ]
    }
  ) });
}
export {
  EntityDetail
};
