import { completeBooking, fetchAllBookings, rescheduleBooking, retryCalendarSync, } from "../api"; import type { Booking } from "../types"; import { calculateInterval, checkBufferCollision, formatCurrency, formatDateInput, formatDateTime, formatTimeOnly, isSameDay, isThisWeek, isToday, isTomorrow, } from "../utils"; import { showConfirmModal } from "./MicroModal"; import { renderBookingStatusBadge, renderCalendarSyncBadge, renderPaymentStatusBadge, } from "./StatusBadge"; import { showToast } from "./Toast"; type AgendaDateFilter = "TODAY" | "TOMORROW" | "THIS_WEEK" | "ALL" | "CUSTOM"; export function renderDailyAgenda( container: HTMLElement, onStateChange: () => void, ): void { let activeFilter: AgendaDateFilter = "TODAY"; let customDateStr: string = ""; let cachedBookings: Booking[] = []; container.innerHTML = `

Agenda & Control de Capacidad

Visualización cronológica con protección de buffers de 15 min entre pacientes.

`; const contentDiv = container.querySelector("#agenda-content"); const statsDiv = container.querySelector("#agenda-stats"); const indicatorDiv = container.querySelector( "#agenda-filter-indicator", ); const refreshBtn = container.querySelector( "#refresh-agenda-btn", ); const customDateInput = container.querySelector( "#agenda-custom-date", ); const filterButtons = container.querySelectorAll(".btn-filter-pill"); const loadData = async () => { if (!contentDiv) return; contentDiv.innerHTML = `
`; try { const bookings = await fetchAllBookings(); cachedBookings = bookings .filter( (b) => b.booking_status !== "CANCELLED" && b.booking_status !== "RELEASED", ) .sort( (a, b) => new Date(a.scheduled_at).getTime() - new Date(b.scheduled_at).getTime(), ); applyFilter(); } catch (err: unknown) { if (contentDiv) { contentDiv.innerHTML = `
⚠️

Error al cargar la agenda

${err instanceof Error ? err.message : "Error desconocido"}

`; contentDiv .querySelector("#retry-agenda-load") ?.addEventListener("click", () => loadData()); } } }; const filterBookings = (): Booking[] => { const now = new Date(); if (activeFilter === "TODAY") { return cachedBookings.filter((b) => isToday(new Date(b.scheduled_at), now), ); } if (activeFilter === "TOMORROW") { return cachedBookings.filter((b) => isTomorrow(new Date(b.scheduled_at), now), ); } if (activeFilter === "THIS_WEEK") { return cachedBookings.filter((b) => isThisWeek(new Date(b.scheduled_at), now), ); } if (activeFilter === "CUSTOM" && customDateStr) { const [year, month, day] = customDateStr.split("-").map(Number); const targetDate = new Date(year, month - 1, day); return cachedBookings.filter((b) => isSameDay(new Date(b.scheduled_at), targetDate), ); } return cachedBookings; }; const updateIndicator = (filteredCount: number) => { if (!indicatorDiv) return; let label = ""; if (activeFilter === "TODAY") { label = `📅 Mostrando citas para: Hoy (${new Intl.DateTimeFormat("es-MX", { dateStyle: "long" }).format(new Date())})`; } else if (activeFilter === "TOMORROW") { const tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1); label = `📅 Mostrando citas para: Mañana (${new Intl.DateTimeFormat("es-MX", { dateStyle: "long" }).format(tomorrow)})`; } else if (activeFilter === "THIS_WEEK") { label = `📅 Mostrando citas para: Esta Semana`; } else if (activeFilter === "CUSTOM" && customDateStr) { const [year, month, day] = customDateStr.split("-").map(Number); const targetDate = new Date(year, month - 1, day); label = `📅 Mostrando citas para el día: ${new Intl.DateTimeFormat("es-MX", { dateStyle: "long" }).format(targetDate)}`; } else { label = "📅 Mostrando: Todas las citas programadas"; } indicatorDiv.innerHTML = ` ${label} ${filteredCount} ${filteredCount === 1 ? "cita activa" : "citas activas"} `; }; const applyFilter = () => { const filtered = filterBookings(); updateIndicator(filtered.length); renderStats(filtered); renderTimeline(filtered); }; const renderStats = (bookings: Booking[]) => { if (!statsDiv) return; const total = bookings.length; const confirmed = bookings.filter( (b) => b.payment_status === "ACKNOWLEDGED", ).length; const pending = bookings.filter( (b) => b.payment_status === "AWAITING_ACKNOWLEDGMENT", ).length; const totalMinutes = bookings.reduce( (acc, b) => acc + (b.duration_minutes || 60) + (b.buffer_minutes || 15), 0, ); const totalHours = (totalMinutes / 60).toFixed(1); statsDiv.innerHTML = `
Citas en Periodo ${total}
Pagos Confirmados ${confirmed}
Pendientes / Prórroga ${pending}
Tiempo Ocupado + Buffer ${totalHours}h
`; }; const renderTimeline = (bookings: Booking[]) => { if (!contentDiv) return; if (bookings.length === 0) { contentDiv.innerHTML = `
📅

Agenda libre en este periodo

No hay citas activas programadas para el filtro seleccionado. Puedes cambiar de fecha o ver "Todas las Citas".

`; return; } contentDiv.innerHTML = `
${bookings .map((b, idx) => { const interval = calculateInterval( b.scheduled_at, b.duration_minutes || 60, b.buffer_minutes || 15, ); // Collision detector with subsequent session let collisionNotice = ""; if (idx < bookings.length - 1) { const nextBooking = bookings[idx + 1]; const collision = checkBufferCollision( b.scheduled_at, b.duration_minutes || 60, b.buffer_minutes || 15, nextBooking.scheduled_at, ); if (collision.hasCollision) { const nextStartStr = formatTimeOnly(nextBooking.scheduled_at); collisionNotice = ` `; } } return `
${interval.startStr} a ${interval.endStr} ${b.duration_minutes || 60} min
${b.booking_code} ${b.service_name || "Consulta"}
${renderBookingStatusBadge(b.booking_status)}
${b.client_name || "Cliente"} 📱 ${b.client_phone || ""}
${formatDateTime(b.scheduled_at)} ${formatCurrency(b.amount_mxn)}
${renderPaymentStatusBadge(b.payment_status, b.payment_arrangement)} ${renderCalendarSyncBadge(b.gcal_sync_status, b.id)}
🌿 Buffer de descanso y preparación (${b.buffer_minutes || 15} min): ${interval.endStr} - ${interval.bufferEndStr}
Tiempo no agendable protegido por el backend.
${ b.booking_status === "RESERVED" ? `
` : "" } ${collisionNotice}
`; }) .join("")}
`; // Attach 'Mover Cita' handlers contentDiv.querySelectorAll(".btn-reschedule-booking").forEach((btn) => { btn.addEventListener("click", () => { const id = btn.getAttribute("data-booking-id"); const booking = bookings.find((b) => b.id === id); if (!booking) return; openRescheduleModal({ booking, onSuccess: (updated) => { showToast( `Cita reagendada para ${formatDateTime(updated.scheduled_at)}`, "success", 5000, { folio: updated.booking_code }, ); loadData(); onStateChange(); }, }); }); }); // Attach 'Concluir Cita' handlers contentDiv.querySelectorAll(".btn-complete-booking").forEach((btn) => { btn.addEventListener("click", () => { const id = btn.getAttribute("data-booking-id"); const booking = bookings.find((b) => b.id === id); if (!booking) return; showConfirmModal({ title: "¿Concluir consulta?", kicker: "Finalización de Sesión", message: `¿Deseas marcar la consulta de ${booking.client_name || "Cliente"} (${booking.booking_code}) como concluida? Se registrará la asistencia y el estado cambiará a CONCLUIDA.`, bookingContext: { bookingCode: booking.booking_code, clientName: booking.client_name, serviceName: booking.service_name, scheduledAtFormatted: formatDateTime(booking.scheduled_at), }, withReasonInput: true, reasonLabel: "Notas clínicas u observaciones de la sesión (opcional):", defaultReason: "", reasonPlaceholder: "Ej. Se completó terapia de sonido; paciente reporta relajación profunda.", confirmText: "✓ Sí, Concluir Cita", cancelText: "Volver", isDanger: false, onConfirm: async (notes) => { await completeBooking(booking.id, { notes: notes || undefined, }); showToast( `Cita ${booking.booking_code} marcada como Concluida`, "success", 5000, { folio: booking.booking_code }, ); loadData(); onStateChange(); }, }); }); }); // Attach retry calendar sync buttons contentDiv.querySelectorAll(".btn-retry-gcal").forEach((btn) => { btn.addEventListener("click", async () => { const id = btn.getAttribute("data-booking-id"); if (!id) return; const origText = btn.textContent; btn.textContent = "⏳..."; try { await retryCalendarSync(id); showToast( "✓ Sincronización exitosa con Google Calendar", "success", 4000, ); loadData(); onStateChange(); } catch (err: unknown) { showToast( err instanceof Error ? err.message : "Error al reintentar sincronización", "error", 5000, ); btn.textContent = origText; } }); }); }; // Event Handlers for Filter Buttons filterButtons.forEach((btn) => { btn.addEventListener("click", () => { const filter = btn.getAttribute("data-filter") as AgendaDateFilter; if (!filter) return; activeFilter = filter; if (customDateInput) customDateInput.value = ""; customDateStr = ""; filterButtons.forEach((b) => { const isCurrent = b === btn; b.classList.toggle("active", isCurrent); b.setAttribute("aria-selected", isCurrent ? "true" : "false"); }); applyFilter(); }); }); // Event Handler for Custom Date Input customDateInput?.addEventListener("change", () => { if (customDateInput.value) { activeFilter = "CUSTOM"; customDateStr = customDateInput.value; filterButtons.forEach((b) => { b.classList.remove("active"); b.setAttribute("aria-selected", "false"); }); applyFilter(); } }); refreshBtn?.addEventListener("click", () => loadData()); loadData(); } interface RescheduleModalOptions { booking: Booking; onSuccess: (updated: Booking) => void; } function openRescheduleModal(options: RescheduleModalOptions): void { const { booking, onSuccess } = options; const existing = document.getElementById("reschedule-modal-backdrop"); if (existing) existing.remove(); const backdrop = document.createElement("div"); backdrop.id = "reschedule-modal-backdrop"; backdrop.className = "modal-backdrop"; const currentDt = new Date(booking.scheduled_at); const defaultDate = formatDateInput(currentDt); const hours = String(currentDt.getHours()).padStart(2, "0"); const mins = String(currentDt.getMinutes()).padStart(2, "0"); const defaultTime = `${hours}:${mins}`; backdrop.innerHTML = ` `; document.body.appendChild(backdrop); const close = () => { backdrop.remove(); document.removeEventListener("keydown", handleKeyDown); }; const handleKeyDown = (e: KeyboardEvent) => { if (e.key === "Escape") close(); }; document.addEventListener("keydown", handleKeyDown); backdrop .querySelector("#reschedule-modal-close") ?.addEventListener("click", () => close()); backdrop .querySelector("#reschedule-cancel-btn") ?.addEventListener("click", () => close()); backdrop.addEventListener("click", (e) => { if (e.target === backdrop) close(); }); const form = backdrop.querySelector("#reschedule-form"); const dateInput = backdrop.querySelector("#reschedule-date"); const timeInput = backdrop.querySelector("#reschedule-time"); const notesInput = backdrop.querySelector("#reschedule-notes"); const submitBtn = backdrop.querySelector( "#reschedule-submit-btn", ); const errorBox = backdrop.querySelector("#reschedule-error"); form?.addEventListener("submit", async (e) => { e.preventDefault(); if (!submitBtn || !errorBox) return; const dVal = dateInput?.value; const tVal = timeInput?.value; const notes = notesInput?.value.trim() || undefined; if (!dVal || !tVal) { errorBox.textContent = "Por favor selecciona la nueva fecha y hora."; errorBox.classList.remove("hidden"); return; } const newDt = new Date(`${dVal}T${tVal}:00`); if (Number.isNaN(newDt.getTime())) { errorBox.textContent = "Fecha u hora inválida."; errorBox.classList.remove("hidden"); return; } submitBtn.disabled = true; submitBtn.textContent = "Reagendando..."; errorBox.classList.add("hidden"); try { const updated = await rescheduleBooking(booking.id, { new_scheduled_at: newDt.toISOString(), notes, }); close(); onSuccess(updated); } catch (err: unknown) { submitBtn.disabled = false; submitBtn.textContent = "Confirmar Nuevo Horario"; errorBox.textContent = err instanceof Error ? err.message : "Error al reagendar la consulta."; errorBox.classList.remove("hidden"); } }); }