import { e as createComponent, k as renderComponent, r as renderTemplate } from '../../chunks/astro/server_CNSJbOTP.mjs';
import 'piccolore';
import { a as api, $ as $$AppLayout } from '../../chunks/AppLayout_DAKNch61.mjs';
import { jsxs, jsx } from 'react/jsx-runtime';
import { useState, useCallback, useEffect } from 'react';
export { renderers } from '../../renderers.mjs';

const ETIQUETAS_ACCION = {
  "auth.login": "Inicio de sesión",
  "auth.logout": "Cierre de sesión",
  "usuario.crear": "Crear usuario",
  "usuario.actualizar": "Actualizar usuario",
  "usuario.desactivar": "Desactivar usuario",
  "usuario.restablecer_contrasena": "Restablecer contraseña",
  "empresa.crear": "Crear empresa",
  "empresa.actualizar": "Actualizar empresa",
  "empresa.desactivar": "Desactivar empresa"
};
function formatearFecha(fecha) {
  return new Date(fecha).toLocaleString("es-CL", {
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit"
  });
}
function RegistroAuditoriaComponent() {
  const [registros, setRegistros] = useState([]);
  const [total, setTotal] = useState(0);
  const [pagina, setPagina] = useState(1);
  const [cargando, setCargando] = useState(true);
  const [error, setError] = useState("");
  const [filtroAccion, setFiltroAccion] = useState("");
  const porPagina = 50;
  const cargar = useCallback(async () => {
    setCargando(true);
    setError("");
    try {
      const params = new URLSearchParams({ pagina: String(pagina), por_pagina: String(porPagina) });
      if (filtroAccion) params.set("accion", filtroAccion);
      const data = await api.get(`/auditoria?${params}`);
      setRegistros(data.datos);
      setTotal(data.total);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Error al cargar auditoría");
    } finally {
      setCargando(false);
    }
  }, [pagina, filtroAccion]);
  useEffect(() => {
    cargar();
  }, [cargar]);
  const totalPaginas = Math.ceil(total / porPagina);
  return /* @__PURE__ */ jsxs("div", { children: [
    /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap gap-3 mb-4 items-center justify-between", children: [
      /* @__PURE__ */ jsxs(
        "select",
        {
          value: filtroAccion,
          onChange: (e) => {
            setFiltroAccion(e.currentTarget.value);
            setPagina(1);
          },
          className: "input w-auto text-sm",
          children: [
            /* @__PURE__ */ jsx("option", { value: "", children: "Todas las acciones" }),
            Object.entries(ETIQUETAS_ACCION).map(([valor, etiqueta]) => /* @__PURE__ */ jsx("option", { value: valor, children: etiqueta }, valor))
          ]
        }
      ),
      /* @__PURE__ */ jsxs("span", { className: "text-sm text-gray-500", children: [
        total,
        " registros"
      ] })
    ] }),
    error && /* @__PURE__ */ jsx("div", { className: "mb-4 p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700", children: error }),
    /* @__PURE__ */ jsx("div", { className: "table-container", children: /* @__PURE__ */ jsxs("table", { className: "table", children: [
      /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { children: [
        /* @__PURE__ */ jsx("th", { children: "Fecha" }),
        /* @__PURE__ */ jsx("th", { children: "Acción" }),
        /* @__PURE__ */ jsx("th", { className: "hidden sm:table-cell", children: "Usuario ID" }),
        /* @__PURE__ */ jsx("th", { className: "hidden md:table-cell", children: "Entidad" }),
        /* @__PURE__ */ jsx("th", { className: "hidden lg:table-cell", children: "IP" })
      ] }) }),
      /* @__PURE__ */ jsx("tbody", { children: cargando ? /* @__PURE__ */ jsx("tr", { children: /* @__PURE__ */ jsx("td", { colSpan: 5, className: "text-center py-10 text-gray-400", children: "Cargando..." }) }) : registros.length === 0 ? /* @__PURE__ */ jsx("tr", { children: /* @__PURE__ */ jsx("td", { colSpan: 5, className: "text-center py-10 text-gray-400", children: "No hay registros" }) }) : registros.map((r) => /* @__PURE__ */ jsxs("tr", { children: [
        /* @__PURE__ */ jsx("td", { className: "text-xs text-gray-500 whitespace-nowrap", children: formatearFecha(r.creado_en) }),
        /* @__PURE__ */ jsx("td", { children: /* @__PURE__ */ jsx("span", { className: "badge badge-info text-xs", children: ETIQUETAS_ACCION[r.accion] || r.accion }) }),
        /* @__PURE__ */ jsxs("td", { className: "hidden sm:table-cell text-gray-600 text-sm", children: [
          "#",
          r.usuario_id ?? "—"
        ] }),
        /* @__PURE__ */ jsx("td", { className: "hidden md:table-cell text-gray-600 text-sm", children: r.entidad_tipo ? `${r.entidad_tipo} #${r.entidad_id}` : "—" }),
        /* @__PURE__ */ jsx("td", { className: "hidden lg:table-cell text-gray-400 text-xs font-mono", children: r.ip_origen || "—" })
      ] }, r.id)) })
    ] }) }),
    totalPaginas > 1 && /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between mt-4 text-sm text-gray-600", children: [
      /* @__PURE__ */ jsxs("span", { children: [
        "Página ",
        pagina,
        " de ",
        totalPaginas
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
        /* @__PURE__ */ jsx("button", { disabled: pagina === 1, onClick: () => setPagina((p) => p - 1), className: "btn-secondary py-1 px-3 text-xs disabled:opacity-50", children: "← Anterior" }),
        /* @__PURE__ */ jsx("button", { disabled: pagina === totalPaginas, onClick: () => setPagina((p) => p + 1), className: "btn-secondary py-1 px-3 text-xs disabled:opacity-50", children: "Siguiente →" })
      ] })
    ] })
  ] });
}

const $$Auditoria = createComponent(($$result, $$props, $$slots) => {
  return renderTemplate`${renderComponent($$result, "AppLayout", $$AppLayout, { "titulo": "Registro de Auditor\xEDa", "seccionActiva": "auditoria" }, { "default": ($$result2) => renderTemplate` ${renderComponent($$result2, "RegistroAuditoria", RegistroAuditoriaComponent, { "client:load": true, "client:component-hydration": "load", "client:component-path": "C:/Proyectos IA/Sistema de Control y Gesti\xF3n Crew Consultores/frontend/src/components/admin/RegistroAuditoria", "client:component-export": "default" })} ` })}`;
}, "C:/Proyectos IA/Sistema de Control y Gesti\xF3n Crew Consultores/frontend/src/pages/admin/auditoria.astro", void 0);

const $$file = "C:/Proyectos IA/Sistema de Control y Gestión Crew Consultores/frontend/src/pages/admin/auditoria.astro";
const $$url = "/admin/auditoria";

const _page = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
  __proto__: null,
  default: $$Auditoria,
  file: $$file,
  url: $$url
}, Symbol.toStringTag, { value: 'Module' }));

const page = () => _page;

export { page };
