"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useCallback, useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { EntityForm } from "../EntityForm.js";
import { EntityDetailHeader } from "../EntityDetailHeader.js";
import { Alert, AlertDescription } from "../../ui/alert.js";
import { SkeletonEntityForm } from "../../ui/skeleton-form.js";
import { useEntityConfig } from "../../../hooks/useEntityConfig.js";
import { useTeam } from "../../../hooks/useTeam.js";
import { getEntityData, createEntityData, updateEntityData } from "../../../lib/api/entities.js";
function EntityFormWrapper({
  entityType,
  mode,
  id,
  initialData: propsInitialData,
  onSuccess,
  onError,
  className,
  headerActions: additionalHeaderActions
}) {
  var _a, _b;
  const router = useRouter();
  const { config: entityConfig, isLoading: isLoadingConfig, error: configError, isOverride } = useEntityConfig(entityType);
  const { teamId } = useTeam();
  const [initialData, setInitialData] = useState(propsInitialData || {});
  const [isLoadingData, setIsLoadingData] = useState(false);
  useEffect(() => {
    if (propsInitialData && Object.keys(propsInitialData).length > 0) {
      setInitialData(propsInitialData);
      return;
    }
    const loadInitialData = async () => {
      if (mode === "edit" && id && entityConfig) {
        if (!entityConfig.enabled) {
          onError == null ? void 0 : onError(new Error(`Entidad "${entityType}" est\xE1 deshabilitada`));
          return;
        }
        try {
          setIsLoadingData(true);
          console.log(`[EntityFormWrapper] Loading data for ${entityType} ${id} (override: ${isOverride})`);
          const data = await getEntityData(entityType, id);
          console.log(`[EntityFormWrapper] Loaded data:`, data);
          setInitialData(data || {});
        } catch (error) {
          console.error(`[EntityFormWrapper] Error loading data for ${entityType} ${id}:`, error);
          onError == null ? void 0 : onError(error instanceof Error ? error : new Error(`Failed to load ${entityType} data`));
        } finally {
          setIsLoadingData(false);
        }
      }
    };
    loadInitialData();
  }, [mode, id, entityType, entityConfig, onError, isOverride, propsInitialData]);
  const handleSubmit = useCallback(async (data) => {
    try {
      console.log(`${mode === "create" ? "Creating" : "Updating"} ${entityType}:`, data);
      if (mode === "create") {
        const created = await createEntityData(entityType, data);
        onSuccess == null ? void 0 : onSuccess(created == null ? void 0 : created.id);
      } else if (mode === "edit" && id) {
        await updateEntityData(entityType, id, data);
        onSuccess == null ? void 0 : onSuccess(id);
      }
    } catch (error) {
      console.error(`\u274C Failed to ${mode} ${entityType}:`, error);
      onError == null ? void 0 : onError(error instanceof Error ? error : new Error(`Failed to ${mode} ${entityType}`));
    }
  }, [entityType, mode, id, onSuccess, onError]);
  if (isLoadingConfig || isLoadingData) {
    const fieldCount = ((_a = entityConfig == null ? void 0 : entityConfig.fields) == null ? void 0 : _a.length) || 8;
    const hasTextareas = true;
    const hasJsonFields = ((_b = entityConfig == null ? void 0 : entityConfig.fields) == null ? void 0 : _b.some(
      (field) => field.type === "json" || field.name.includes("Values") || field.name.includes("Languages")
    )) || false;
    return /* @__PURE__ */ jsx(
      SkeletonEntityForm,
      {
        fieldCount,
        hasTextareas,
        hasJsonFields
      }
    );
  }
  if (configError || !entityConfig) {
    return /* @__PURE__ */ jsx(Alert, { children: /* @__PURE__ */ jsx(AlertDescription, { children: configError || `No se pudo cargar la configuraci\xF3n para la entidad "${entityType}".` }) });
  }
  const customActions = additionalHeaderActions ? /* @__PURE__ */ jsx(Fragment, { children: additionalHeaderActions }) : void 0;
  return /* @__PURE__ */ jsx("div", { className: "p-6", children: /* @__PURE__ */ jsxs("div", { className: "max-w-7xl mx-auto space-y-6", children: [
    /* @__PURE__ */ jsx(
      EntityDetailHeader,
      {
        entityConfig,
        mode,
        entity: mode === "edit" && initialData.id ? {
          id: String(initialData.id),
          createdAt: initialData.createdAt,
          updatedAt: initialData.updatedAt,
          title: initialData.title,
          name: initialData.name,
          ...initialData
        } : void 0,
        customActions
      }
    ),
    /* @__PURE__ */ jsx(
      EntityForm,
      {
        entityConfig,
        mode,
        initialData,
        onSubmit: handleSubmit,
        className,
        teamId
      }
    )
  ] }) });
}
export {
  EntityFormWrapper
};
