import { useReservations } from "@/features/reservations/hooks/useReservations"; import theme from "@/theme"; import { MaterialIcons } from "@expo/vector-icons"; import { useRouter } from "expo-router"; import { useState } from "react"; import { ActivityIndicator, Alert, Platform, Pressable, ScrollView, StyleSheet, Text, View, } from "react-native"; const { colors, spacing, radius, typography, fontWeight, layout, shadows } = theme; function getReservationWindowStart(date: string, startTime: string): Date { return new Date(`${date}T${startTime}:00`); } function getReservationWindowEnd(date: string, endTime: string): Date { return new Date(`${date}T${endTime}:00`); } function canCheckIn(date: string, startTime: string, endTime: string): boolean { const now = new Date(); const reservationStart = getReservationWindowStart(date, startTime); const reservationEnd = getReservationWindowEnd(date, endTime); // permitir check-in desde 30 minutos antes de la hora de la reserva const checkInOpensAt = new Date(reservationStart.getTime() - 30 * 60 * 1000); return now >= checkInOpensAt && now <= reservationEnd; } function hasToDate(value: unknown): value is { toDate: () => Date } { return ( !!value && typeof value === "object" && "toDate" in value && typeof value.toDate === "function" ); } function formatCheckInAt(value: unknown): string { if (!hasToDate(value)) { return "Registrada"; } const date = value.toDate(); if (!(date instanceof Date) || Number.isNaN(date.getTime())) { return "Registrada"; } return new Intl.DateTimeFormat("es-ES", { dateStyle: "short", timeStyle: "short", }).format(date); } export default function ReservationsScreen() { // router para navegar a otras pantallas const router = useRouter(); // hook principal de reservas const { activeReservations, historyReservations, loading, error, reload, cancelReservation, cancelingReservationId, checkingInReservationId, checkInReservation, } = useReservations(); // controla la pestaña visible de reservas const [activeTab, setActiveTab] = useState<"active" | "history">("active"); // confirmacion antes de cancelar una reserva // en web usamos window.confirm porque Alert puede no comportarse bien const handleCancelReservation = (reservationId: string) => { if (Platform.OS === "web") { const confirmed = window.confirm( "Esta acción marcará la reserva como cancelada.", ); if (confirmed) { void cancelReservation(reservationId); } return; } // en movil sigue usando el Alert Alert.alert( "Cancelar reserva", "Esta acción marcará la reserva como cancelada.", [ { text: "Volver", style: "cancel" }, { text: "Cancelar reserva", style: "destructive", onPress: () => { void cancelReservation(reservationId); }, }, ], ); }; // estado de carga general if (loading) { return ( ); } // estado de error general if (error) { return ( {error} Reintentar ); } return ( {/* cabecera superior */} Mis reservas {/* pestañas superiores */} setActiveTab("active")} > Activas ({activeReservations.length}) setActiveTab("history")} > Historial ({historyReservations.length}) {/* seccion de reservas activas */} {activeTab === "active" ? ( Activas {activeReservations.length === 0 ? ( No tienes reservas activas Cuando realices una nueva reserva, aparecerá aquí. ) : ( activeReservations.map((item) => ( {/* cabecera de la tarjeta */} {item.officeName} Reserva activa Activa {/* detalles de la reserva */} {item.date} {item.startTime} - {item.endTime} {item.checkInAt ? `Llegada registrada: ${formatCheckInAt(item.checkInAt)}` : "Llegada pendiente"} {/* linea separadora antes de acciones */} {/* boton de check-in solo visible cuando se puede hacer check-in */} {!item.checkInAt && canCheckIn(item.date, item.startTime, item.endTime) ? ( { void checkInReservation(item.id); }} disabled={checkingInReservationId === item.id} > {checkingInReservationId === item.id ? "Registrando llegada..." : "He llegado"} ) : null} {/* fila de acciones secundarias */} {/* boton editar reserva */} [ styles.editButton, pressed && styles.editButtonPressed, ]} onPress={() => { // navegar a create en modo edicion, pasando los parametros necesarios router.push({ pathname: "/(protected)/reservations/create", params: { mode: "edit", reservationId: item.id, officeId: item.officeId, officeName: item.officeName, oldDate: item.date, oldStartTime: item.startTime, oldEndTime: item.endTime, }, }); }} > Editar {/* boton cancelar */} [ styles.cancelButton, pressed && styles.cancelButtonPressed, ]} onPress={() => handleCancelReservation(item.id)} disabled={cancelingReservationId === item.id} > {cancelingReservationId === item.id ? "Cancelando..." : "Cancelar"} )) )} ) : null} {/* seccion historial */} {activeTab === "history" ? ( Historial {historyReservations.length === 0 ? ( No tienes historial Aquí verás tus reservas completadas o canceladas. ) : ( historyReservations.map((item) => ( {/* cabecera de la tarjeta */} {item.officeName} Reserva finalizada {item.status === "completed" ? "Completada" : "Cancelada"} {/* detalles de historial */} {item.date} {item.startTime} - {item.endTime} {item.checkInAt ? `Llegada registrada: ${formatCheckInAt(item.checkInAt)}` : "Llegada no registrada"} )) )} ) : null} ); } const styles = StyleSheet.create({ // contenedor principal container: { flex: 1, backgroundColor: colors.background, }, // cabecera superior de la pantalla topBar: { backgroundColor: colors.surface, borderBottomWidth: 1, borderBottomColor: colors.border, paddingHorizontal: spacing.xl, paddingTop: spacing.xxxl, paddingBottom: spacing.lg, }, // titulo de la cabecera topBarTitle: { fontSize: typography.xxl, fontWeight: fontWeight.semibold, color: colors.text, textAlign: "left", maxWidth: layout.contentWidth, width: "100%", alignSelf: "center", }, // scroll principal scroll: { flex: 1, backgroundColor: colors.background, }, // contenido interno del scroll content: { paddingHorizontal: spacing.xl, paddingTop: spacing.lg, paddingBottom: spacing.xxxl, gap: spacing.xl, maxWidth: layout.contentWidth, width: "100%", alignSelf: "center", }, // estado de carga / error center: { flex: 1, alignItems: "center", justifyContent: "center", padding: spacing.xxxl, gap: spacing.md, backgroundColor: colors.background, }, // seccion general section: { gap: spacing.md, }, // cabecera de seccion sectionHeader: { flexDirection: "row", alignItems: "center", justifyContent: "space-between", }, // titulo de seccion sectionTitle: { fontSize: typography.xl, fontWeight: fontWeight.semibold, color: colors.text, }, // fila de pestañas superiores tabsRow: { flexDirection: "row", gap: spacing.sm, backgroundColor: "#E9EEF5", borderRadius: radius.xxl, padding: spacing.xs, }, // boton de pestaña tabButton: { flex: 1, paddingVertical: spacing.md, borderRadius: radius.xl, alignItems: "center", }, // boton activo tabButtonActive: { backgroundColor: colors.surface, ...shadows.card, }, // texto de pestaña tabButtonText: { color: colors.textSecondary, fontSize: typography.md, fontWeight: fontWeight.medium, }, // texto de pestaña activa tabButtonTextActive: { color: colors.text, }, // tarjeta base de reserva card: { backgroundColor: colors.surface, borderRadius: radius.xxl, padding: spacing.lg, borderWidth: 1, borderColor: colors.border, gap: spacing.md, ...shadows.card, }, // cabecera de la tarjeta cardHeader: { flexDirection: "row", alignItems: "flex-start", justifyContent: "space-between", gap: spacing.md, }, // bloque izquierdo de la cabecera de la card cardHeaderLeft: { flexDirection: "row", alignItems: "flex-start", gap: spacing.md, flex: 1, }, // contenedor del icono del edificio cardIconWrap: { width: 40, height: 40, borderRadius: radius.md, backgroundColor: colors.primarySoft, alignItems: "center", justifyContent: "center", }, // bloque de titulo de tarjeta cardTitleBlock: { flex: 1, gap: 2, }, // titulo principal de la reserva cardTitle: { fontSize: typography.lg, fontWeight: fontWeight.semibold, color: colors.text, }, // subtitulo pequeño cardSubtitle: { fontSize: typography.sm, color: colors.textSecondary, }, // badge comun de estado statusBadge: { borderRadius: 999, paddingHorizontal: spacing.sm, paddingVertical: spacing.xs, }, // estado activa statusActive: { backgroundColor: "#DCFCE7", }, // estado completada statusCompleted: { backgroundColor: "#DBEAFE", }, // estado cancelada statusCancelled: { backgroundColor: "#FEE2E2", }, // texto base del estado statusText: { fontSize: typography.xs, fontWeight: fontWeight.semibold, }, // color texto activa statusTextActive: { color: "#166534", }, // color texto completada statusTextCompleted: { color: "#1D4ED8", }, // color texto cancelada statusTextCancelled: { color: "#B91C1C", }, // lista de detalles detailsList: { gap: spacing.sm, }, // fila individual de detalle detailRow: { flexDirection: "row", alignItems: "center", gap: spacing.sm, }, // texto del detalle detailText: { fontSize: typography.md, color: colors.textSecondary, flex: 1, }, // linea separadora antes de acciones cardDivider: { height: 1, backgroundColor: colors.divider, marginTop: spacing.xs, }, // boton principal de reintento primaryButton: { backgroundColor: colors.primary, paddingHorizontal: spacing.xl, paddingVertical: spacing.md, borderRadius: radius.md, alignItems: "center", }, // texto del boton principal primaryButtonText: { color: colors.white, fontWeight: fontWeight.semibold, }, // boton de check-in checkInButton: { backgroundColor: colors.successBg, paddingVertical: spacing.md, borderRadius: radius.md, alignItems: "center", marginTop: spacing.xs, }, // texto del boton de check-in checkInButtonText: { color: colors.successText, fontWeight: fontWeight.semibold, }, // fila de acciones secundarias // coloca editar a la izquierda y cancelar a la derecha actionsRow: { flexDirection: "row", justifyContent: "space-between", alignItems: "center", marginTop: spacing.xs, }, // boton editar reserva editButton: { paddingVertical: spacing.sm, paddingHorizontal: spacing.md, borderRadius: radius.md, backgroundColor: colors.surface, alignItems: "center", justifyContent: "center", }, // estado pulsado del boton editar editButtonPressed: { backgroundColor: "#EAF2FF", }, // texto del boton editar editButtonText: { color: colors.primary, fontWeight: fontWeight.medium, fontSize: typography.sm, }, // boton cancelar reserva cancelButton: { paddingVertical: spacing.sm, paddingHorizontal: spacing.md, borderRadius: radius.md, backgroundColor: colors.surface, alignItems: "center", justifyContent: "center", }, // estado pulsado del boton cancelar cancelButtonPressed: { backgroundColor: "#FEECEC", }, // texto del boton cancelar cancelButtonText: { color: "#DC2626", fontWeight: fontWeight.medium, fontSize: typography.sm, }, // contenido interno del boton cancelar cancelContent: { flexDirection: "row", alignItems: "center", gap: spacing.xs, }, // tarjeta vacia emptyCard: { backgroundColor: colors.surface, borderRadius: radius.xxl, padding: spacing.lg, borderWidth: 1, borderColor: colors.border, gap: spacing.xs, }, // titulo de estado vacio emptyTitle: { fontSize: typography.md, fontWeight: fontWeight.semibold, color: colors.text, }, // texto de estado vacio emptyText: { fontSize: typography.sm, color: colors.textSecondary, lineHeight: 18, }, // error general error: { color: colors.error, textAlign: "center", }, });