import { S as reactExports, J as jsxRuntimeExports } from "./server-CZT6KZsz.js";
import { u as useQuery, a as TriangleAlert, T as Trash2 } from "./triangle-alert-Bg0uC9pN.js";
import { Q as useAuth, U as useQueryClient, l as formatARS, G as stockQO, O as toast, H as supabase } from "./router-Bsssaenw.js";
import { B as Button, P as Plus, E as useMutation, b as Dialog, c as DialogContent, f as DialogHeader, g as DialogTitle, L as Label, I as Input, T as Textarea, e as DialogFooter, X } from "./textarea-BUwzaNv6.js";
import { A as AppShell } from "./AppShell-CCqmKL3X.js";
import { c as createLucideIcon, L as LoaderCircle } from "./wrench-CccwRKu3.js";
import { P as Package } from "./package-D5atLoEx.js";
import { P as Pencil } from "./pencil-B5jF51ki.js";
import { C as Check } from "./check-CKvikDYV.js";
import "node:async_hooks";
import "node:stream/web";
import "node:stream";
const __iconNode = [
  ["path", { d: "m3 16 4 4 4-4", key: "1co6wj" }],
  ["path", { d: "M7 20V4", key: "1yoxec" }],
  ["path", { d: "m21 8-4-4-4 4", key: "1c9v7m" }],
  ["path", { d: "M17 4v16", key: "7dpous" }]
];
const ArrowDownUp = createLucideIcon("arrow-down-up", __iconNode);
function StockPage() {
  const {
    role,
    loading
  } = useAuth();
  const qc = useQueryClient();
  const q = useQuery(stockQO());
  const items = q.data ?? [];
  const [editing, setEditing] = reactExports.useState(null);
  const [creating, setCreating] = reactExports.useState(false);
  const [reposicion, setReposicion] = reactExports.useState(null);
  if (loading) return /* @__PURE__ */ jsxRuntimeExports.jsx(AppShell, { children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid place-items-center py-20", children: /* @__PURE__ */ jsxRuntimeExports.jsx(LoaderCircle, { className: "size-6 animate-spin text-muted-foreground" }) }) });
  if (role !== "admin") {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(AppShell, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "max-w-md mx-auto mt-20 text-center space-y-2", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("h1", { className: "text-xl font-display font-bold", children: "Acceso restringido" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-muted-foreground", children: "Solo administradores pueden gestionar el stock." })
    ] }) });
  }
  const totalValor = items.reduce((acc, i) => acc + Number(i.stock_actual) * Number(i.costo_unitario ?? 0), 0);
  const bajos = items.filter((i) => Number(i.stock_actual) <= Number(i.stock_minimo));
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(AppShell, { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-end justify-between gap-4 flex-wrap", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("h1", { className: "text-3xl font-display font-bold tracking-tight", children: "Stock de materiales" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-muted-foreground mt-1", children: "Catálogo central que se descuenta automáticamente al cargar materiales en una OS." })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { onClick: () => setCreating(true), className: "gradient-primary text-primary-foreground", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "size-4 mr-2" }),
          " Nuevo material"
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-3 gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Stat, { label: "Ítems en catálogo", value: String(items.length) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Stat, { label: "Valor en stock", value: formatARS(totalValor) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Stat, { label: "Por reponer", value: String(bajos.length), variant: bajos.length > 0 ? "warn" : "ok" })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "border border-border rounded-lg overflow-hidden bg-card", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("table", { className: "w-full text-sm", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("thead", { className: "bg-muted/50 text-xs uppercase tracking-wider text-muted-foreground font-mono", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("tr", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("th", { className: "text-left px-4 py-3", children: "Material" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("th", { className: "text-right px-4 py-3", children: "Stock" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("th", { className: "text-right px-4 py-3", children: "Mínimo" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("th", { className: "text-right px-4 py-3", children: "$ unit." }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("th", { className: "text-right px-4 py-3", children: "Valor" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("th", { className: "px-4 py-3" })
        ] }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("tbody", { className: "divide-y divide-border", children: [
          items.length === 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("tr", { children: /* @__PURE__ */ jsxRuntimeExports.jsxs("td", { colSpan: 6, className: "text-center py-12 text-muted-foreground text-sm", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Package, { className: "size-6 mx-auto mb-2 opacity-50" }),
            " Sin materiales en catálogo"
          ] }) }),
          items.map((m) => {
            const bajo = Number(m.stock_actual) <= Number(m.stock_minimo);
            const cu = m.costo_unitario != null ? Number(m.costo_unitario) : null;
            return /* @__PURE__ */ jsxRuntimeExports.jsxs("tr", { className: "hover:bg-muted/30", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("td", { className: "px-4 py-3", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "font-medium", children: m.nombre }),
                m.unidad && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-[11px] text-muted-foreground font-mono", children: m.unidad }),
                m.notas && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-muted-foreground mt-0.5", children: m.notas })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: "px-4 py-3 text-right font-mono", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: bajo ? "text-destructive font-semibold inline-flex items-center gap-1" : "", children: [
                bajo && /* @__PURE__ */ jsxRuntimeExports.jsx(TriangleAlert, { className: "size-3.5" }),
                Number(m.stock_actual)
              ] }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: "px-4 py-3 text-right font-mono text-muted-foreground", children: Number(m.stock_minimo) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: "px-4 py-3 text-right font-mono", children: cu != null ? formatARS(cu) : "—" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: "px-4 py-3 text-right font-mono", children: cu != null ? formatARS(cu * Number(m.stock_actual)) : "—" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: "px-4 py-3 text-right", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "inline-flex items-center gap-1", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { size: "sm", variant: "ghost", onClick: () => setReposicion(m), title: "Ajustar stock", children: /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowDownUp, { className: "size-4" }) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { size: "sm", variant: "ghost", onClick: () => setEditing(m), title: "Editar", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Pencil, { className: "size-4" }) })
              ] }) })
            ] }, m.id);
          })
        ] })
      ] }) })
    ] }),
    creating && /* @__PURE__ */ jsxRuntimeExports.jsx(EditDialog, { onClose: () => setCreating(false), onSaved: () => {
      qc.invalidateQueries({
        queryKey: ["stock"]
      });
      setCreating(false);
    } }),
    editing && /* @__PURE__ */ jsxRuntimeExports.jsx(EditDialog, { item: editing, onClose: () => setEditing(null), onSaved: () => {
      qc.invalidateQueries({
        queryKey: ["stock"]
      });
      setEditing(null);
    } }),
    reposicion && /* @__PURE__ */ jsxRuntimeExports.jsx(ReposicionDialog, { item: reposicion, onClose: () => setReposicion(null), onSaved: () => {
      qc.invalidateQueries({
        queryKey: ["stock"]
      });
      setReposicion(null);
    } })
  ] });
}
function Stat({
  label,
  value,
  variant
}) {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "rounded-lg border border-border bg-card px-4 py-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-[11px] uppercase tracking-wider text-muted-foreground font-mono", children: label }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: `text-2xl font-display font-bold mt-1 ${variant === "warn" ? "text-destructive" : ""}`, children: value })
  ] });
}
function EditDialog({
  item,
  onClose,
  onSaved
}) {
  const [nombre, setNombre] = reactExports.useState(item?.nombre ?? "");
  const [unidad, setUnidad] = reactExports.useState(item?.unidad ?? "");
  const [stockActual, setStockActual] = reactExports.useState(String(item?.stock_actual ?? 0));
  const [stockMin, setStockMin] = reactExports.useState(String(item?.stock_minimo ?? 0));
  const [costo, setCosto] = reactExports.useState(item?.costo_unitario != null ? String(item.costo_unitario) : "");
  const [notas, setNotas] = reactExports.useState(item?.notas ?? "");
  const guardar = useMutation({
    mutationFn: async () => {
      if (!nombre.trim()) throw new Error("Nombre requerido");
      const payload = {
        nombre: nombre.trim(),
        unidad: unidad.trim() || null,
        stock_actual: Number(stockActual) || 0,
        stock_minimo: Number(stockMin) || 0,
        costo_unitario: costo ? Number(costo) : null,
        notas: notas.trim() || null
      };
      if (item) {
        const {
          error
        } = await supabase.from("materiales_stock").update(payload).eq("id", item.id);
        if (error) throw error;
      } else {
        const {
          error
        } = await supabase.from("materiales_stock").insert(payload);
        if (error) throw error;
      }
    },
    onSuccess: () => {
      toast.success(item ? "Material actualizado" : "Material creado");
      onSaved();
    },
    onError: (e) => toast.error(e.message)
  });
  const eliminar = useMutation({
    mutationFn: async () => {
      if (!item) return;
      const {
        error
      } = await supabase.from("materiales_stock").delete().eq("id", item.id);
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success("Material eliminado del catálogo");
      onSaved();
    },
    onError: (e) => toast.error(e.message)
  });
  return /* @__PURE__ */ jsxRuntimeExports.jsx(Dialog, { open: true, onOpenChange: onClose, children: /* @__PURE__ */ jsxRuntimeExports.jsxs(DialogContent, { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(DialogHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(DialogTitle, { className: "font-display", children: item ? "Editar material" : "Nuevo material" }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-1.5", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Label, { children: "Nombre *" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Input, { value: nombre, onChange: (e) => setNombre(e.target.value), placeholder: "Ej. Cable 2.5mm" })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-2 gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-1.5", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Label, { children: "Unidad" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(Input, { value: unidad, onChange: (e) => setUnidad(e.target.value), placeholder: "m, u, kg…" })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-1.5", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Label, { children: "Costo unitario" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(Input, { type: "number", min: "0", step: "0.01", value: costo, onChange: (e) => setCosto(e.target.value) })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-2 gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-1.5", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Label, { children: "Stock actual" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(Input, { type: "number", step: "0.01", value: stockActual, onChange: (e) => setStockActual(e.target.value) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-1.5", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Label, { children: "Stock mínimo" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(Input, { type: "number", min: "0", step: "0.01", value: stockMin, onChange: (e) => setStockMin(e.target.value) })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-1.5", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Label, { children: "Notas" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Textarea, { rows: 2, value: notas, onChange: (e) => setNotas(e.target.value), className: "resize-none" })
      ] })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(DialogFooter, { className: "gap-2", children: [
      item && /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { variant: "outline", onClick: () => eliminar.mutate(), disabled: eliminar.isPending, className: "mr-auto text-destructive hover:text-destructive", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "size-4 mr-1" }),
        " Eliminar"
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { variant: "outline", onClick: onClose, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "size-4 mr-1" }),
        " Cancelar"
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { onClick: () => guardar.mutate(), disabled: guardar.isPending, className: "gradient-primary text-primary-foreground", children: [
        guardar.isPending ? /* @__PURE__ */ jsxRuntimeExports.jsx(LoaderCircle, { className: "size-4 animate-spin mr-1" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Check, { className: "size-4 mr-1" }),
        " Guardar"
      ] })
    ] })
  ] }) });
}
function ReposicionDialog({
  item,
  onClose,
  onSaved
}) {
  const [tipo, setTipo] = reactExports.useState("sumar");
  const [cantidad, setCantidad] = reactExports.useState("");
  const aplicar = useMutation({
    mutationFn: async () => {
      const n = Number(cantidad);
      if (!n || n < 0) throw new Error("Cantidad inválida");
      const actual = Number(item.stock_actual);
      const nuevo = tipo === "sumar" ? actual + n : tipo === "restar" ? actual - n : n;
      const {
        error
      } = await supabase.from("materiales_stock").update({
        stock_actual: nuevo
      }).eq("id", item.id);
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success("Stock actualizado");
      onSaved();
    },
    onError: (e) => toast.error(e.message)
  });
  return /* @__PURE__ */ jsxRuntimeExports.jsx(Dialog, { open: true, onOpenChange: onClose, children: /* @__PURE__ */ jsxRuntimeExports.jsxs(DialogContent, { className: "sm:max-w-md", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(DialogHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(DialogTitle, { className: "font-display", children: [
      "Ajustar stock · ",
      item.nombre
    ] }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-sm text-muted-foreground", children: [
        "Actual: ",
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-mono font-semibold text-foreground", children: Number(item.stock_actual) }),
        item.unidad ? ` ${item.unidad}` : ""
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-3 gap-1 p-1 bg-muted rounded-md", children: ["sumar", "restar", "ajustar"].map((t) => /* @__PURE__ */ jsxRuntimeExports.jsx("button", { onClick: () => setTipo(t), className: `text-xs py-2 rounded font-medium transition-colors ${tipo === t ? "bg-card shadow-sm" : "text-muted-foreground hover:text-foreground"}`, children: t === "sumar" ? "Reponer (+)" : t === "restar" ? "Restar (−)" : "Ajustar a" }, t)) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Input, { type: "number", min: "0", step: "0.01", placeholder: "Cantidad", value: cantidad, onChange: (e) => setCantidad(e.target.value), autoFocus: true }),
      cantidad && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-muted-foreground font-mono", children: [
        "Resultado:",
        " ",
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-semibold text-foreground", children: tipo === "sumar" ? Number(item.stock_actual) + Number(cantidad) : tipo === "restar" ? Number(item.stock_actual) - Number(cantidad) : Number(cantidad) })
      ] })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(DialogFooter, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { variant: "outline", onClick: onClose, children: "Cancelar" }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { onClick: () => aplicar.mutate(), disabled: aplicar.isPending || !cantidad, className: "gradient-primary text-primary-foreground", children: [
        aplicar.isPending && /* @__PURE__ */ jsxRuntimeExports.jsx(LoaderCircle, { className: "size-4 animate-spin mr-1" }),
        " Aplicar"
      ] })
    ] })
  ] }) });
}
export {
  StockPage as component
};
