"use client";
import { jsx } from "react/jsx-runtime";
import React, { useState, useEffect, useCallback, useMemo } from "react";
import { EntityDetail } from "../EntityDetail.js";
import { Alert, AlertDescription } from "../../ui/alert.js";
import { SkeletonEntityDetail } from "../../ui/skeleton-detail.js";
import { useEntityConfig } from "../../../hooks/useEntityConfig.js";
import { useRouter } from "next/navigation";
import { getEntityData, deleteEntityData, fetchWithTeam } from "../../../lib/api/entities.js";
import { TeamDetailSection } from "../../teams/TeamDetailSection.js";
function EntityDetailWrapper({
  entityType,
  id,
  childEntityNames = [],
  onError,
  className,
  customFormComponents = {}
}) {
  const { config: entityConfig, isLoading: isLoadingConfig, error: configError, isOverride } = useEntityConfig(entityType);
  const router = useRouter();
  const [data, setData] = useState(null);
  const [childData, setChildData] = useState({});
  const [isLoadingData, setIsLoadingData] = useState(false);
  const [dataError, setDataError] = useState(null);
  const hasChildEntities = childEntityNames.length > 0;
  const customSections = useMemo(() => {
    const sections = [];
    if (entityType === "teams") {
      sections.push({
        id: "team-members",
        component: ({ data: data2 }) => /* @__PURE__ */ jsx(TeamDetailSection, { teamId: String(data2.id) }),
        position: "after-details"
      });
    }
    return sections;
  }, [entityType]);
  const loadChildEntitiesData = useCallback(async (parentId) => {
    console.log(`[loadChildEntitiesData] Called with parentId:`, parentId, `childEntityNames:`, childEntityNames);
    if (!hasChildEntities) {
      console.log(`[loadChildEntitiesData] No child entities found, returning early`);
      return;
    }
    try {
      const childrenData = {};
      console.log(`[loadChildEntitiesData] Starting to load child entities:`, childEntityNames);
      for (const childName of childEntityNames) {
        try {
          console.log(`[EntityDetailWrapper] Loading child data for ${childName}`);
          const response = await fetchWithTeam(`/api/v1/${entityType}/${parentId}/child/${childName}`, {
            method: "GET"
          });
          if (response.ok) {
            const result = await response.json();
            const childRows = result.success ? result.data : [];
            console.log(`[EntityDetailWrapper] Loaded ${childRows.length} ${childName} records`);
            childrenData[childName] = childRows;
          } else {
            console.warn(`Failed to load child data for ${childName}: ${response.status}`);
            childrenData[childName] = [];
          }
        } catch (error) {
          console.warn(`Failed to load child data for ${childName}:`, error);
          childrenData[childName] = [];
        }
      }
      console.log(`[loadChildEntitiesData] Setting child data:`, childrenData);
      setChildData(childrenData);
    } catch (error) {
      console.error("Error loading child entities data:", error);
    }
  }, [childEntityNames, hasChildEntities, entityType]);
  const dataLoadedRef = React.useRef(false);
  const prevIdRef = React.useRef(null);
  useEffect(() => {
    if (prevIdRef.current !== id) {
      dataLoadedRef.current = false;
      prevIdRef.current = id;
    }
    if (!entityConfig || !id) return;
    if (dataLoadedRef.current) return;
    if (!entityConfig.enabled) {
      const error = new Error(`Entidad "${entityType}" est\xE1 deshabilitada`);
      setDataError(error.message);
      onError == null ? void 0 : onError(error);
      return;
    }
    const loadEntityData = async () => {
      try {
        setIsLoadingData(true);
        setDataError(null);
        console.log(`[EntityDetailWrapper] Loading data for "${entityType}" id: ${id} (override: ${isOverride})`);
        console.log(`[EntityDetailWrapper] hasChildEntities:`, hasChildEntities);
        if (hasChildEntities) {
          const endpointPath = entityConfig.slug || `${entityType}s`;
          const url = new URL(`/api/v1/${endpointPath}/${id}`, window.location.origin);
          url.searchParams.set("child", "all");
          url.searchParams.set("metas", "all");
          console.log(`[EntityDetailWrapper] Loading parent+child data from:`, url.toString());
          const response = await fetchWithTeam(url.toString(), {
            method: "GET"
          });
          if (!response.ok) {
            throw new Error(`Failed to load ${entityType} with children: ${response.status}`);
          }
          const apiResult = await response.json();
          console.log(`[EntityDetailWrapper] Received parent+child data:`, apiResult);
          const result = apiResult.data;
          console.log(`[EntityDetailWrapper] result.child:`, result.child);
          console.log(`[EntityDetailWrapper] typeof result.child:`, typeof result.child);
          setData(result);
          if (result.child) {
            console.log(`[EntityDetailWrapper] Setting child data from combined response:`, result.child);
            setChildData(result.child);
          } else {
            console.log(`[EntityDetailWrapper] No result.child found, setting empty childData`);
            setChildData({});
          }
        } else {
          const result = await getEntityData(entityType, id, true);
          console.log(`[EntityDetailWrapper] Loaded data for "${entityType}" ${id}:`, result);
          setData(result);
        }
        setDataError(null);
        dataLoadedRef.current = true;
      } catch (err) {
        console.error(`[EntityDetailWrapper] Error loading data for "${entityType}" ${id}:`, err);
        const errorMessage = `Error cargando datos: ${err instanceof Error ? err.message : "Error desconocido"}`;
        setDataError(errorMessage);
        setData(null);
        if (onError) {
          onError(err instanceof Error ? err : new Error(errorMessage));
        }
      } finally {
        setIsLoadingData(false);
      }
    };
    loadEntityData();
  }, [entityConfig == null ? void 0 : entityConfig.slug, entityType, id]);
  const handleEdit = useCallback(() => {
    router.push(`/dashboard/${entityConfig == null ? void 0 : entityConfig.slug}/${id}/edit`);
  }, [router, entityConfig, id]);
  const handleDelete = useCallback(async () => {
    try {
      await deleteEntityData(entityType, id);
      router.push(`/dashboard/${(entityConfig == null ? void 0 : entityConfig.slug) || entityType}`);
    } catch (error) {
      console.error("Error deleting entity:", error);
      onError == null ? void 0 : onError(error instanceof Error ? error : new Error("Error deleting entity"));
      throw error;
    }
  }, [entityType, id, router, entityConfig, onError]);
  const handleRefresh = useCallback(async () => {
    if (!entityConfig || !id) return;
    try {
      setIsLoadingData(true);
      setDataError(null);
      dataLoadedRef.current = false;
      if (hasChildEntities) {
        const endpointPath = entityConfig.slug || `${entityType}s`;
        const url = new URL(`/api/v1/${endpointPath}/${id}`, window.location.origin);
        url.searchParams.set("child", "all");
        url.searchParams.set("metas", "all");
        const response = await fetchWithTeam(url.toString(), {
          method: "GET"
        });
        if (!response.ok) {
          throw new Error(`Failed to reload ${entityType} with children: ${response.status}`);
        }
        const apiResult = await response.json();
        const result = apiResult.data;
        setData(result);
        if (result.child) {
          setChildData(result.child);
        }
      } else {
        const result = await getEntityData(entityType, id, true);
        setData(result);
      }
      setDataError(null);
    } catch (err) {
      console.error(`[EntityDetailWrapper] Error reloading data:`, err);
      const errorMessage = `Error recargando datos: ${err instanceof Error ? err.message : "Error desconocido"}`;
      setDataError(errorMessage);
    } finally {
      setIsLoadingData(false);
    }
  }, [entityConfig, entityType, id, hasChildEntities]);
  const handleChildAdd = useCallback(async (childName, childData2) => {
    try {
      console.log(`[EntityDetailWrapper] Adding child ${childName} for parent ${id}`, childData2);
      const endpointPath = (entityConfig == null ? void 0 : entityConfig.slug) || `${entityType}s`;
      const url = `/api/v1/${endpointPath}/${id}/child/${childName}`;
      console.log(`[EntityDetailWrapper] Calling URL: ${url}`);
      console.log(`[EntityDetailWrapper] Sending data:`, JSON.stringify(childData2, null, 2));
      const response = await fetchWithTeam(url, {
        method: "POST",
        body: JSON.stringify(childData2)
      });
      console.log(`[EntityDetailWrapper] Response status: ${response.status}`);
      if (!response.ok) {
        const errorText = await response.text();
        console.log(`[EntityDetailWrapper] Error response: ${errorText}`);
        throw new Error(`Failed to create ${childName}: ${response.status}`);
      }
      const result = await response.json();
      if (!result.success || !result.data) {
        throw new Error("Invalid response format");
      }
      setChildData((prev) => ({
        ...prev,
        [childName]: [...prev[childName] || [], result.data]
      }));
    } catch (error) {
      console.error(`Error creating child ${childName}:`, error);
      throw error;
    }
  }, [id, entityType, entityConfig]);
  const handleChildEdit = useCallback(async (childName, childId, childData2) => {
    try {
      console.log(`[EntityDetailWrapper] Editing child ${childName} with id ${childId}`, childData2);
      const endpointPath = (entityConfig == null ? void 0 : entityConfig.slug) || `${entityType}s`;
      const response = await fetchWithTeam(`/api/v1/${endpointPath}/${id}/child/${childName}/${childId}`, {
        method: "PUT",
        body: JSON.stringify(childData2)
      });
      if (!response.ok) {
        throw new Error(`Failed to update ${childName}: ${response.status}`);
      }
      const result = await response.json();
      if (!result.success || !result.data) {
        throw new Error("Invalid response format");
      }
      setChildData((prev) => ({
        ...prev,
        [childName]: (prev[childName] || []).map(
          (item) => String(item.id) === childId ? result.data : item
        )
      }));
    } catch (error) {
      console.error(`Error updating child ${childName}:`, error);
      throw error;
    }
  }, [id, entityType, entityConfig]);
  const handleChildDelete = useCallback(async (childName, childId) => {
    try {
      console.log(`[EntityDetailWrapper] Deleting child ${childName} with id ${childId}`);
      const endpointPath = (entityConfig == null ? void 0 : entityConfig.slug) || `${entityType}s`;
      const response = await fetchWithTeam(`/api/v1/${endpointPath}/${id}/child/${childName}/${childId}`, {
        method: "DELETE"
      });
      if (!response.ok) {
        throw new Error(`Failed to delete ${childName}: ${response.status}`);
      }
      setChildData((prev) => ({
        ...prev,
        [childName]: (prev[childName] || []).filter(
          (item) => String(item.id) !== childId
        )
      }));
    } catch (error) {
      console.error(`Error deleting child ${childName}:`, error);
      throw error;
    }
  }, [id, entityType, entityConfig]);
  if (isLoadingConfig) {
    return /* @__PURE__ */ jsx(SkeletonEntityDetail, {});
  }
  if (configError || !entityConfig) {
    return /* @__PURE__ */ jsx(Alert, { children: /* @__PURE__ */ jsx(AlertDescription, { children: configError || `No se pudo cargar la configuraci\xF3n para la entidad "${entityType}".` }) });
  }
  if (isLoadingData) {
    return /* @__PURE__ */ jsx(SkeletonEntityDetail, {});
  }
  if (dataError) {
    return /* @__PURE__ */ jsx(Alert, { children: /* @__PURE__ */ jsx(AlertDescription, { children: dataError }) });
  }
  if (!data) {
    return /* @__PURE__ */ jsx(Alert, { children: /* @__PURE__ */ jsx(AlertDescription, { children: "No se encontraron datos para esta entidad." }) });
  }
  return /* @__PURE__ */ jsx(
    EntityDetail,
    {
      entityConfig,
      data,
      childData,
      childEntityNames,
      isLoading: isLoadingData,
      error: dataError,
      onEdit: handleEdit,
      onDelete: handleDelete,
      onChildAdd: handleChildAdd,
      onChildEdit: handleChildEdit,
      onChildDelete: handleChildDelete,
      onRefresh: handleRefresh,
      enableActions: true,
      className,
      customFormComponents,
      customSections
    }
  );
}
export {
  EntityDetailWrapper
};
