import { S as reactExports, J as jsxRuntimeExports } from "./server-CZT6KZsz.js";
import { u as useSuspenseQuery } from "./useSuspenseQuery-CRUy30GM.js";
import { A as AppShell, B as Building2 } from "./AppShell-CCqmKL3X.js";
import { U as useQueryClient, O as toast, H as supabase, c as administracionesQO, o as getInitials, l as formatARS } from "./router-Bsssaenw.js";
import { 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, B as Button, P as Plus } from "./textarea-BUwzaNv6.js";
import { M as Mail, P as Phone } from "./phone-CwN74hQO.js";
import { P as Pencil } from "./pencil-B5jF51ki.js";
import "node:async_hooks";
import "node:stream/web";
import "node:stream";
import "./package-D5atLoEx.js";
import "./wrench-CccwRKu3.js";
function NuevaAdministracionDialog({ open, onOpenChange }) {
  const qc = useQueryClient();
  const [form, setForm] = reactExports.useState({
    nombre: "",
    cuit: "",
    contacto: "",
    email: "",
    telefono: "",
    abono_mensual: "",
    dia_cobro: "",
    notas: ""
  });
  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));
  const mut = useMutation({
    mutationFn: async () => {
      if (!form.nombre.trim()) throw new Error("El nombre es obligatorio");
      const payload = {
        nombre: form.nombre.trim(),
        cuit: form.cuit.trim() || null,
        contacto: form.contacto.trim() || null,
        email: form.email.trim() || null,
        telefono: form.telefono.trim() || null,
        abono_mensual: form.abono_mensual ? Number(form.abono_mensual) : 0,
        dia_cobro: form.dia_cobro ? Number(form.dia_cobro) : null,
        notas: form.notas.trim() || null
      };
      const { error } = await supabase.from("administraciones").insert(payload);
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success("Administración creada");
      qc.invalidateQueries({ queryKey: ["administraciones"] });
      setForm({ nombre: "", cuit: "", contacto: "", email: "", telefono: "", abono_mensual: "", dia_cobro: "", notas: "" });
      onOpenChange(false);
    },
    onError: (e) => toast.error(e.message ?? "Error al crear")
  });
  return /* @__PURE__ */ jsxRuntimeExports.jsx(Dialog, { open, onOpenChange, children: /* @__PURE__ */ jsxRuntimeExports.jsxs(DialogContent, { className: "max-w-lg", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(DialogHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(DialogTitle, { children: "Nueva Administración" }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid gap-3 py-2", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid gap-1.5", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Label, { children: "Nombre *" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Input, { value: form.nombre, onChange: set("nombre"), autoFocus: true })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-2 gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid gap-1.5", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Label, { children: "CUIT" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(Input, { value: form.cuit, onChange: set("cuit") })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid gap-1.5", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Label, { children: "Contacto" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(Input, { value: form.contacto, onChange: set("contacto") })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-2 gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid gap-1.5", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Label, { children: "Email" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(Input, { type: "email", value: form.email, onChange: set("email") })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid gap-1.5", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Label, { children: "Teléfono" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(Input, { value: form.telefono, onChange: set("telefono") })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-2 gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid gap-1.5", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Label, { children: "Abono mensual" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(Input, { type: "number", min: "0", step: "0.01", value: form.abono_mensual, onChange: set("abono_mensual") })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid gap-1.5", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Label, { children: "Día de cobro" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(Input, { type: "number", min: "1", max: "31", value: form.dia_cobro, onChange: set("dia_cobro") })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid gap-1.5", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Label, { children: "Notas" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Textarea, { rows: 3, value: form.notas, onChange: set("notas") })
      ] })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(DialogFooter, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { variant: "outline", onClick: () => onOpenChange(false), disabled: mut.isPending, children: "Cancelar" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { onClick: () => mut.mutate(), disabled: mut.isPending, children: mut.isPending ? "Creando..." : "Crear" })
    ] })
  ] }) });
}
const empty = { nombre: "", direccion: "", cuit: "", pisos: "", unidades: "", observaciones: "" };
function EdificioDialog({ open, onOpenChange, administracionId, administracionNombre, edificio }) {
  const qc = useQueryClient();
  const isEdit = !!edificio?.id;
  const [form, setForm] = reactExports.useState(empty);
  reactExports.useEffect(() => {
    if (open) {
      setForm({
        nombre: edificio?.nombre ?? "",
        direccion: edificio?.direccion ?? "",
        cuit: edificio?.cuit ?? "",
        pisos: edificio?.pisos != null ? String(edificio.pisos) : "",
        unidades: edificio?.unidades != null ? String(edificio.unidades) : "",
        observaciones: edificio?.observaciones ?? ""
      });
    }
  }, [open, edificio]);
  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));
  const mut = useMutation({
    mutationFn: async () => {
      if (!form.nombre.trim()) throw new Error("El nombre es obligatorio");
      if (!form.direccion.trim()) throw new Error("La dirección es obligatoria");
      const payload = {
        administracion_id: administracionId,
        nombre: form.nombre.trim(),
        direccion: form.direccion.trim(),
        cuit: form.cuit.trim() || null,
        pisos: form.pisos ? Number(form.pisos) : null,
        unidades: form.unidades ? Number(form.unidades) : null,
        observaciones: form.observaciones.trim() || null
      };
      if (isEdit && edificio?.id) {
        const { error } = await supabase.from("edificios").update(payload).eq("id", edificio.id);
        if (error) throw error;
      } else {
        const { error } = await supabase.from("edificios").insert(payload);
        if (error) throw error;
      }
    },
    onSuccess: () => {
      toast.success(isEdit ? "Edificio actualizado" : "Edificio creado");
      qc.invalidateQueries({ queryKey: ["administraciones"] });
      onOpenChange(false);
    },
    onError: (e) => toast.error(e.message ?? "Error")
  });
  const del = useMutation({
    mutationFn: async () => {
      if (!edificio?.id) return;
      const { error } = await supabase.from("edificios").delete().eq("id", edificio.id);
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success("Edificio eliminado");
      qc.invalidateQueries({ queryKey: ["administraciones"] });
      onOpenChange(false);
    },
    onError: (e) => toast.error(e.message ?? "Error al eliminar")
  });
  return /* @__PURE__ */ jsxRuntimeExports.jsx(Dialog, { open, onOpenChange, children: /* @__PURE__ */ jsxRuntimeExports.jsxs(DialogContent, { className: "max-w-lg", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(DialogHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(DialogTitle, { children: [
      isEdit ? "Editar edificio" : "Nuevo edificio",
      administracionNombre && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-sm text-muted-foreground font-normal ml-2", children: [
        "· ",
        administracionNombre
      ] })
    ] }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid gap-3 py-2", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid gap-1.5", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Label, { children: "Nombre *" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Input, { value: form.nombre, onChange: set("nombre"), autoFocus: true })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid gap-1.5", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Label, { children: "Dirección *" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Input, { value: form.direccion, onChange: set("direccion") })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid gap-1.5", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Label, { children: "CUIT" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Input, { value: form.cuit, onChange: set("cuit"), placeholder: "XX-XXXXXXXX-X" })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-2 gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid gap-1.5", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Label, { children: "Pisos" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(Input, { type: "number", min: "0", value: form.pisos, onChange: set("pisos") })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid gap-1.5", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Label, { children: "Unidades" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(Input, { type: "number", min: "0", value: form.unidades, onChange: set("unidades") })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid gap-1.5", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Label, { children: "Observaciones" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Textarea, { rows: 3, value: form.observaciones, onChange: set("observaciones") })
      ] })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(DialogFooter, { className: "gap-2 sm:justify-between", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: isEdit && /* @__PURE__ */ jsxRuntimeExports.jsx(
        Button,
        {
          variant: "destructive",
          onClick: () => {
            if (confirm("¿Eliminar este edificio?")) del.mutate();
          },
          disabled: del.isPending || mut.isPending,
          children: "Eliminar"
        }
      ) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { variant: "outline", onClick: () => onOpenChange(false), disabled: mut.isPending, children: "Cancelar" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { onClick: () => mut.mutate(), disabled: mut.isPending, children: mut.isPending ? "Guardando..." : isEdit ? "Guardar" : "Crear" })
      ] })
    ] })
  ] }) });
}
function AdminsPage() {
  const {
    data: administraciones
  } = useSuspenseQuery(administracionesQO());
  const [open, setOpen] = reactExports.useState(false);
  const [edif, setEdif] = reactExports.useState(null);
  const totalEdif = administraciones.reduce((s, a) => s + (a.edificios?.length ?? 0), 0);
  return /* @__PURE__ */ jsxRuntimeExports.jsx(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("div", { className: "text-xs uppercase tracking-widest text-muted-foreground font-mono", children: "Macro · Consorcios" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("h1", { className: "text-3xl font-bold mt-1", children: "Administraciones" }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-muted-foreground mt-1", children: [
          administraciones.length,
          " administraciones · ",
          totalEdif,
          " edificios bajo abono"
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("button", { onClick: () => setOpen(true), className: "inline-flex items-center gap-2 px-4 py-2.5 rounded-md gradient-primary text-primary-foreground font-medium text-sm shadow-elevated", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "size-4" }),
        " Nueva Administración"
      ] })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(NuevaAdministracionDialog, { open, onOpenChange: setOpen }),
    edif && /* @__PURE__ */ jsxRuntimeExports.jsx(EdificioDialog, { open: !!edif, onOpenChange: (v) => !v && setEdif(null), administracionId: edif.adminId, administracionNombre: edif.adminNombre, edificio: edif.edificio }),
    administraciones.length === 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "bg-card border border-border rounded-xl p-10 text-center text-sm text-muted-foreground", children: "Aún no cargaste administraciones." }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid lg:grid-cols-2 gap-4", children: administraciones.map((a) => {
      const edifs = a.edificios ?? [];
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-card border border-border rounded-xl shadow-card overflow-hidden", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "p-5 flex items-start gap-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "size-12 rounded-lg gradient-primary grid place-items-center text-primary-foreground font-bold shrink-0", children: getInitials(a.nombre) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1 min-w-0", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start justify-between gap-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "font-display font-semibold", children: a.nombre }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-muted-foreground", children: a.contacto ?? "Sin contacto" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-right", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "font-mono font-bold text-sm", children: formatARS(Number(a.abono_mensual ?? 0)) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-[10px] uppercase tracking-wider text-muted-foreground", children: "Abono / mes" })
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-3 flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted-foreground", children: [
              a.email && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "inline-flex items-center gap-1", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Mail, { className: "size-3" }),
                " ",
                a.email
              ] }),
              a.telefono && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "inline-flex items-center gap-1", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Phone, { className: "size-3" }),
                " ",
                a.telefono
              ] })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "border-t border-border bg-muted/20", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "px-5 py-2 text-[11px] uppercase tracking-wider text-muted-foreground font-mono flex items-center justify-between gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "inline-flex items-center gap-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Building2, { className: "size-3" }),
              " ",
              edifs.length,
              " edificio",
              edifs.length === 1 ? "" : "s",
              " bajo gestión"
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("button", { onClick: () => setEdif({
              adminId: a.id,
              adminNombre: a.nombre,
              edificio: null
            }), className: "inline-flex items-center gap-1 text-primary hover:underline normal-case tracking-normal text-xs", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "size-3" }),
              " Agregar"
            ] })
          ] }),
          edifs.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "divide-y divide-border", children: edifs.map((e) => /* @__PURE__ */ jsxRuntimeExports.jsxs("button", { onClick: () => setEdif({
            adminId: a.id,
            adminNombre: a.nombre,
            edificio: e
          }), className: "w-full px-5 py-2.5 flex items-center justify-between hover:bg-card transition-colors text-left", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm font-medium", children: e.nombre }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-muted-foreground", children: [
                e.direccion,
                e.pisos ? ` · ${e.pisos} pisos` : "",
                e.unidades ? ` · ${e.unidades} unidades` : ""
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(Pencil, { className: "size-3.5 text-muted-foreground" })
          ] }, e.id)) })
        ] })
      ] }, a.id);
    }) })
  ] }) });
}
export {
  AdminsPage as component
};
