"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import React from "react";
import { Alert, AlertDescription, AlertTitle } from "../ui/alert.js";
import { Button } from "../ui/button.js";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "../ui/card.js";
import { AlertTriangle, RefreshCw, Home, Bug } from "lucide-react";
class EntityErrorBoundary extends React.Component {
  retryCount = 0;
  maxRetries = 3;
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }
  static getDerivedStateFromError(error) {
    const errorId = `entity-error-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
    return {
      hasError: true,
      error,
      errorId
    };
  }
  componentDidCatch(error, errorInfo) {
    const { entityType, onError } = this.props;
    const { errorId } = this.state;
    console.group(`\u{1F6A8} Entity Error Boundary [${entityType || "Unknown"}]`);
    console.error("Error ID:", errorId);
    console.error("Error:", error);
    console.error("Error Info:", errorInfo);
    console.error("Component Stack:", errorInfo.componentStack);
    console.error("Retry Count:", this.retryCount);
    console.groupEnd();
    this.setState({
      errorInfo
    });
    if (onError) {
      onError(error, errorInfo);
    }
    this.reportError(error, errorInfo, entityType);
  }
  reportError = async (error, errorInfo, entityType) => {
    try {
      const errorReport = {
        message: error.message,
        stack: error.stack,
        componentStack: errorInfo.componentStack,
        entityType,
        errorId: this.state.errorId,
        timestamp: (/* @__PURE__ */ new Date()).toISOString(),
        url: typeof window !== "undefined" ? window.location.href : "",
        userAgent: typeof window !== "undefined" ? window.navigator.userAgent : ""
      };
      console.log("\u{1F4CA} Error Report:", errorReport);
    } catch (reportingError) {
      console.error("Failed to report error:", reportingError);
    }
  };
  handleRetry = () => {
    if (this.retryCount < this.maxRetries) {
      this.retryCount++;
      console.log(`\u{1F504} Retrying entity component (attempt ${this.retryCount}/${this.maxRetries})`);
      this.setState({
        hasError: false,
        error: void 0,
        errorInfo: void 0
      });
    }
  };
  handleReset = () => {
    this.retryCount = 0;
    this.setState({
      hasError: false,
      error: void 0,
      errorInfo: void 0
    });
  };
  handleReload = () => {
    if (typeof window !== "undefined") {
      window.location.reload();
    }
  };
  handleGoHome = () => {
    if (typeof window !== "undefined") {
      window.location.href = "/dashboard";
    }
  };
  getErrorType = (error) => {
    if (error.message.includes("network") || error.message.includes("fetch")) {
      return "network";
    }
    if (error.message.includes("permission") || error.message.includes("auth")) {
      return "permission";
    }
    if (error.message.includes("not found") || error.message.includes("404")) {
      return "not-found";
    }
    if (error.message.includes("config") || error.message.includes("registry")) {
      return "configuration";
    }
    return "unknown";
  };
  getErrorMessage = (error, entityType) => {
    const errorType = this.getErrorType(error);
    const entityName = entityType ? ` de ${entityType}` : "";
    switch (errorType) {
      case "network":
        return {
          title: "Error de Conexi\xF3n",
          description: `No se pudo conectar con el servidor para cargar los datos${entityName}. Verifica tu conexi\xF3n a internet.`
        };
      case "permission":
        return {
          title: "Sin Permisos",
          description: `No tienes los permisos necesarios para acceder a estos datos${entityName}.`
        };
      case "not-found":
        return {
          title: "Recurso No Encontrado",
          description: `Los datos${entityName} que solicitas no est\xE1n disponibles o han sido eliminados.`
        };
      case "configuration":
        return {
          title: "Error de Configuraci\xF3n",
          description: `Hay un problema con la configuraci\xF3n${entityName}. Contacta al administrador.`
        };
      default:
        return {
          title: "Error Inesperado",
          description: `Ha ocurrido un error inesperado${entityName}. Nuestro equipo ha sido notificado.`
        };
    }
  };
  render() {
    const { hasError, error, errorInfo, errorId } = this.state;
    const { children, fallback, entityType, showDetails = false } = this.props;
    if (hasError && error) {
      if (fallback) {
        return fallback;
      }
      const { title, description } = this.getErrorMessage(error, entityType);
      const canRetry = this.retryCount < this.maxRetries;
      const errorType = this.getErrorType(error);
      return /* @__PURE__ */ jsx("div", { className: "min-h-[400px] flex items-center justify-center p-6", children: /* @__PURE__ */ jsxs(Card, { className: "w-full max-w-2xl", children: [
        /* @__PURE__ */ jsxs(CardHeader, { className: "text-center", children: [
          /* @__PURE__ */ jsx("div", { className: "mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-red-100", children: /* @__PURE__ */ jsx(AlertTriangle, { className: "h-6 w-6 text-red-600" }) }),
          /* @__PURE__ */ jsx(CardTitle, { className: "text-xl font-semibold text-gray-900", children: title }),
          /* @__PURE__ */ jsx(CardDescription, { className: "text-base text-gray-600", children: description })
        ] }),
        /* @__PURE__ */ jsxs(CardContent, { className: "space-y-6", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap gap-3 justify-center", children: [
            canRetry && /* @__PURE__ */ jsxs(
              Button,
              {
                onClick: this.handleRetry,
                variant: "default",
                className: "inline-flex items-center",
                children: [
                  /* @__PURE__ */ jsx(RefreshCw, { className: "h-4 w-4 mr-2" }),
                  "Reintentar (",
                  this.maxRetries - this.retryCount,
                  " intentos restantes)"
                ]
              }
            ),
            /* @__PURE__ */ jsxs(
              Button,
              {
                onClick: this.handleReset,
                variant: "outline",
                className: "inline-flex items-center",
                children: [
                  /* @__PURE__ */ jsx(RefreshCw, { className: "h-4 w-4 mr-2" }),
                  "Restablecer"
                ]
              }
            ),
            /* @__PURE__ */ jsxs(
              Button,
              {
                onClick: this.handleGoHome,
                variant: "outline",
                className: "inline-flex items-center",
                children: [
                  /* @__PURE__ */ jsx(Home, { className: "h-4 w-4 mr-2" }),
                  "Ir al Dashboard"
                ]
              }
            ),
            /* @__PURE__ */ jsxs(
              Button,
              {
                onClick: this.handleReload,
                variant: "ghost",
                className: "inline-flex items-center",
                children: [
                  /* @__PURE__ */ jsx(RefreshCw, { className: "h-4 w-4 mr-2" }),
                  "Recargar P\xE1gina"
                ]
              }
            )
          ] }),
          (showDetails || process.env.NODE_ENV === "development") && errorInfo && /* @__PURE__ */ jsxs(Alert, { children: [
            /* @__PURE__ */ jsx(Bug, { className: "h-4 w-4" }),
            /* @__PURE__ */ jsx(AlertTitle, { children: "Detalles del Error (Desarrollo)" }),
            /* @__PURE__ */ jsx(AlertDescription, { className: "mt-2", children: /* @__PURE__ */ jsxs("div", { className: "space-y-2 text-sm font-mono", children: [
              /* @__PURE__ */ jsxs("div", { children: [
                /* @__PURE__ */ jsx("strong", { children: "Error ID:" }),
                " ",
                errorId
              ] }),
              /* @__PURE__ */ jsxs("div", { children: [
                /* @__PURE__ */ jsx("strong", { children: "Tipo:" }),
                " ",
                errorType
              ] }),
              /* @__PURE__ */ jsxs("div", { children: [
                /* @__PURE__ */ jsx("strong", { children: "Entidad:" }),
                " ",
                entityType || "N/A"
              ] }),
              /* @__PURE__ */ jsxs("div", { children: [
                /* @__PURE__ */ jsx("strong", { children: "Mensaje:" }),
                " ",
                error.message
              ] }),
              error.stack && /* @__PURE__ */ jsxs("details", { className: "mt-2", children: [
                /* @__PURE__ */ jsx("summary", { className: "cursor-pointer font-semibold", children: "Stack Trace" }),
                /* @__PURE__ */ jsx("pre", { className: "mt-2 overflow-auto text-xs bg-gray-100 p-2 rounded", children: error.stack })
              ] }),
              errorInfo.componentStack && /* @__PURE__ */ jsxs("details", { className: "mt-2", children: [
                /* @__PURE__ */ jsx("summary", { className: "cursor-pointer font-semibold", children: "Component Stack" }),
                /* @__PURE__ */ jsx("pre", { className: "mt-2 overflow-auto text-xs bg-gray-100 p-2 rounded", children: errorInfo.componentStack })
              ] })
            ] }) })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "text-center text-sm text-gray-500", children: [
            "Si el problema persiste, contacta al soporte t\xE9cnico con el ID: ",
            /* @__PURE__ */ jsx("code", { className: "bg-gray-100 px-1 rounded", children: errorId })
          ] })
        ] })
      ] }) });
    }
    return children;
  }
}
function useEntityErrorHandler(entityType) {
  const handleError = React.useCallback((error, errorInfo) => {
    console.error(`Entity Error in ${entityType}:`, error, errorInfo);
  }, [entityType]);
  return { handleError };
}
function withEntityErrorBoundary(Component, entityType) {
  const WrappedComponent = (props) => /* @__PURE__ */ jsx(EntityErrorBoundary, { entityType, children: /* @__PURE__ */ jsx(Component, { ...props }) });
  WrappedComponent.displayName = `withEntityErrorBoundary(${Component.displayName || Component.name})`;
  return WrappedComponent;
}
export {
  EntityErrorBoundary,
  useEntityErrorHandler,
  withEntityErrorBoundary
};
