import { T as reactExports, K as jsxRuntimeExports } from "./server-ChzsfjB9.js";
import { h as useNavigate, f as useAuth, s as supabase } from "./router-uu4vGjiO.js";
import { a as AppLayout, S as ScrollText, C as Card, g as CardHeader, h as CardTitle, f as CardContent } from "./card-HyNxoILF.js";
import { I as Input, L as LoaderCircle } from "./input-muzHTpl5.js";
import { B as Badge } from "./badge-DHuXnmRX.js";
import { T as Table, d as TableHeader, e as TableRow, c as TableHead, a as TableBody, b as TableCell } from "./table-utS1tm4O.js";
import "node:async_hooks";
import "node:stream/web";
import "node:stream";
import "./index-BxBx9O65.js";
function LogsPage() {
  const navigate = useNavigate();
  const {
    user,
    loading
  } = useAuth();
  const [logs, setLogs] = reactExports.useState([]);
  const [loadingLogs, setLoadingLogs] = reactExports.useState(true);
  const [filter, setFilter] = reactExports.useState("");
  reactExports.useEffect(() => {
    if (!loading && (!user || user.role !== "admin")) {
      navigate({
        to: "/"
      });
    }
  }, [user, loading, navigate]);
  reactExports.useEffect(() => {
    if (user?.role !== "admin") return;
    (async () => {
      setLoadingLogs(true);
      const {
        data: rows
      } = await supabase.from("logs_acesso").select("*").order("criado_em", {
        ascending: false
      }).limit(500);
      const userIds = Array.from(new Set((rows ?? []).map((r) => r.user_id).filter(Boolean)));
      const cliIds = Array.from(new Set((rows ?? []).map((r) => r.cliente_id).filter(Boolean)));
      const [{
        data: perfis
      }, {
        data: clientes
      }] = await Promise.all([userIds.length ? supabase.from("perfis_usuarios").select("id, email").in("id", userIds) : Promise.resolve({
        data: []
      }), cliIds.length ? supabase.from("clientes").select("id, nome_fantasia").in("id", cliIds) : Promise.resolve({
        data: []
      })]);
      const emailMap = new Map((perfis ?? []).map((p) => [p.id, p.email]));
      const cliMap = new Map((clientes ?? []).map((c) => [c.id, c.nome_fantasia]));
      setLogs((rows ?? []).map((r) => ({
        ...r,
        user_email: r.user_id ? emailMap.get(r.user_id) : void 0,
        cliente_nome: r.cliente_id ? cliMap.get(r.cliente_id) : void 0
      })));
      setLoadingLogs(false);
    })();
  }, [user?.role]);
  const filtered = logs.filter((l) => {
    if (!filter.trim()) return true;
    const q = filter.toLowerCase();
    return l.acao?.toLowerCase().includes(q) || l.user_email?.toLowerCase().includes(q) || l.cliente_nome?.toLowerCase().includes(q) || l.ip?.toLowerCase().includes(q);
  });
  return /* @__PURE__ */ jsxRuntimeExports.jsx(AppLayout, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10 text-primary", children: /* @__PURE__ */ jsxRuntimeExports.jsx(ScrollText, { className: "h-5 w-5" }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("h1", { className: "text-2xl font-bold tracking-tight", children: "Logs de acesso" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-muted-foreground", children: "Histórico de logins e ações realizadas no sistema." })
      ] })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs(CardHeader, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: "Eventos recentes" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Input, { placeholder: "Filtrar por ação, e-mail, cliente ou IP...", value: filter, onChange: (e) => setFilter(e.target.value), className: "max-w-md" })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: loadingLogs ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center justify-center py-10 text-muted-foreground", children: /* @__PURE__ */ jsxRuntimeExports.jsx(LoaderCircle, { className: "h-5 w-5 animate-spin" }) }) : filtered.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "py-10 text-center text-sm text-muted-foreground", children: "Nenhum log encontrado." }) : /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "overflow-x-auto", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Table, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(TableHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(TableRow, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(TableHead, { children: "Data" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(TableHead, { children: "Ação" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(TableHead, { children: "Usuário" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(TableHead, { children: "Cliente" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(TableHead, { children: "IP" })
        ] }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(TableBody, { children: filtered.map((l) => /* @__PURE__ */ jsxRuntimeExports.jsxs(TableRow, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(TableCell, { className: "whitespace-nowrap text-xs text-muted-foreground", children: new Date(l.criado_em).toLocaleString("pt-BR") }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(TableCell, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { variant: "secondary", className: "capitalize", children: l.acao }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(TableCell, { className: "text-sm", children: l.user_email ?? "—" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(TableCell, { className: "text-sm", children: l.cliente_nome ?? "—" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(TableCell, { className: "text-xs text-muted-foreground", children: l.ip ?? "—" })
        ] }, l.id)) })
      ] }) }) })
    ] })
  ] }) });
}
export {
  LogsPage as component
};
