informe-comercial-alfa/app/components/nuevas/MesesControl.js

78 lines
2.6 KiB
JavaScript
Raw Permalink Normal View History

"use client";
import { useState, useRef, useEffect } from "react";
import { useRouter, useSearchParams, usePathname } from "next/navigation";
// Multiselect de Mes de creación de la cohorte. Mismo patrón que OwnerControl: estado en la URL
// (`meses=2026-05,2026-06`), sin el param = todos los meses marcados. No se puede dejar en 0.
export default function MesesControl({ opciones, seleccion }) {
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
const [open, setOpen] = useState(false);
const ref = useRef(null);
const [selected, setSelected] = useState(() => new Set(seleccion));
const selRef = useRef(selected);
const key = seleccion.join(",");
useEffect(() => {
const next = new Set(seleccion);
selRef.current = next;
setSelected(next);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [key]);
useEffect(() => {
function onDocClick(e) {
if (ref.current && !ref.current.contains(e.target)) setOpen(false);
}
document.addEventListener("mousedown", onDocClick);
return () => document.removeEventListener("mousedown", onDocClick);
}, []);
function applySet(nextSet) {
selRef.current = nextSet;
setSelected(nextSet);
const params = new URLSearchParams(searchParams.toString());
if (nextSet.size === opciones.length) params.delete("meses");
else params.set("meses", opciones.filter((o) => nextSet.has(o.k)).map((o) => o.k).join(","));
const qs = params.toString();
router.push(qs ? `${pathname}?${qs}` : pathname, { scroll: false });
}
function toggle(k) {
const next = new Set(selRef.current);
if (next.has(k)) next.delete(k);
else next.add(k);
if (next.size === 0) return;
applySet(next);
}
const label =
selected.size === opciones.length
? "Todos los meses"
: selected.size === 1
? opciones.find((o) => selected.has(o.k))?.lbl
: `${selected.size} meses`;
return (
<div className="ctrl owner-ctrl" ref={ref}>
<label>Mes de creación</label>
<button type="button" className="owner-btn" onClick={() => setOpen((o) => !o)}>
{label}
</button>
<div className={`owner-panel${open ? " open" : ""}`}>
<div className="oa">
<a onClick={() => applySet(new Set(opciones.map((o) => o.k)))}>Todos</a>
</div>
{opciones.map((o) => (
<label className="owner-row" key={o.k}>
<input type="checkbox" checked={selected.has(o.k)} onChange={() => toggle(o.k)} />
{" "}
{o.lbl}
</label>
))}
</div>
</div>
);
}