summaryrefslogtreecommitdiffstats
path: root/src/app/(protected)/(tabs)/reservations/index.tsx
blob: e790cb414718531ceeb039917f3ff42c32f8efb5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
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 (
      <View style={styles.center}>
        <ActivityIndicator size="large" />
      </View>
    );
  }

  // estado de error general
  if (error) {
    return (
      <View style={styles.center}>
        <Text style={styles.error}>{error}</Text>

        <Pressable style={styles.primaryButton} onPress={reload}>
          <Text style={styles.primaryButtonText}>Reintentar</Text>
        </Pressable>
      </View>
    );
  }

  return (
    <View style={styles.container}>
      {/* cabecera superior */}
      <View style={styles.topBar}>
        <Text style={styles.topBarTitle}>Mis reservas</Text>
      </View>

      <ScrollView
        style={styles.scroll}
        contentContainerStyle={styles.content}
        showsVerticalScrollIndicator={false}
      >
        {/* pestañas superiores */}
        <View style={styles.tabsRow}>
          <Pressable
            style={[
              styles.tabButton,
              activeTab === "active" && styles.tabButtonActive,
            ]}
            onPress={() => setActiveTab("active")}
          >
            <Text
              style={[
                styles.tabButtonText,
                activeTab === "active" && styles.tabButtonTextActive,
              ]}
            >
              Activas ({activeReservations.length})
            </Text>
          </Pressable>

          <Pressable
            style={[
              styles.tabButton,
              activeTab === "history" && styles.tabButtonActive,
            ]}
            onPress={() => setActiveTab("history")}
          >
            <Text
              style={[
                styles.tabButtonText,
                activeTab === "history" && styles.tabButtonTextActive,
              ]}
            >
              Historial ({historyReservations.length})
            </Text>
          </Pressable>
        </View>

        {/* seccion de reservas activas */}
        {activeTab === "active" ? (
          <View style={styles.section}>
            <View style={styles.sectionHeader}>
              <Text style={styles.sectionTitle}>Activas</Text>
            </View>

            {activeReservations.length === 0 ? (
              <View style={styles.emptyCard}>
                <Text style={styles.emptyTitle}>
                  No tienes reservas activas
                </Text>
                <Text style={styles.emptyText}>
                  Cuando realices una nueva reserva, aparecerá aquí.
                </Text>
              </View>
            ) : (
              activeReservations.map((item) => (
                <View key={item.id} style={styles.card}>
                  {/* cabecera de la tarjeta */}
                  <View style={styles.cardHeader}>
                    <View style={styles.cardHeaderLeft}>
                      <View style={styles.cardIconWrap}>
                        <MaterialIcons
                          name="business"
                          size={22}
                          color={colors.primary}
                        />
                      </View>

                      <View style={styles.cardTitleBlock}>
                        <Text style={styles.cardTitle}>{item.officeName}</Text>
                        <Text style={styles.cardSubtitle}>Reserva activa</Text>
                      </View>
                    </View>

                    <View style={[styles.statusBadge, styles.statusActive]}>
                      <Text
                        style={[styles.statusText, styles.statusTextActive]}
                      >
                        Activa
                      </Text>
                    </View>
                  </View>

                  {/* detalles de la reserva */}
                  <View style={styles.detailsList}>
                    <View style={styles.detailRow}>
                      <MaterialIcons
                        name="calendar-month"
                        size={16}
                        color={colors.textSecondary}
                      />
                      <Text style={styles.detailText}>{item.date}</Text>
                    </View>

                    <View style={styles.detailRow}>
                      <MaterialIcons
                        name="schedule"
                        size={16}
                        color={colors.textSecondary}
                      />
                      <Text style={styles.detailText}>
                        {item.startTime} - {item.endTime}
                      </Text>
                    </View>

                    <View style={styles.detailRow}>
                      <MaterialIcons
                        name="login"
                        size={16}
                        color={colors.textSecondary}
                      />
                      <Text style={styles.detailText}>
                        {item.checkInAt
                          ? `Llegada registrada: ${formatCheckInAt(item.checkInAt)}`
                          : "Llegada pendiente"}
                      </Text>
                    </View>
                  </View>

                  {/* linea separadora antes de acciones */}
                  <View style={styles.cardDivider} />

                  {/* boton de check-in solo visible cuando se puede hacer check-in */}
                  {!item.checkInAt &&
                  canCheckIn(item.date, item.startTime, item.endTime) ? (
                    <Pressable
                      style={styles.checkInButton}
                      onPress={() => {
                        void checkInReservation(item.id);
                      }}
                      disabled={checkingInReservationId === item.id}
                    >
                      <Text style={styles.checkInButtonText}>
                        {checkingInReservationId === item.id
                          ? "Registrando llegada..."
                          : "He llegado"}
                      </Text>
                    </Pressable>
                  ) : null}

                  {/* fila de acciones secundarias */}
                  <View style={styles.actionsRow}>
                    {/* boton editar reserva */}
                    <Pressable
                      style={({ pressed }) => [
                        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,
                          },
                        });
                      }}
                    >
                      <Text style={styles.editButtonText}>Editar</Text>
                    </Pressable>

                    {/* boton cancelar */}
                    <Pressable
                      style={({ pressed }) => [
                        styles.cancelButton,
                        pressed && styles.cancelButtonPressed,
                      ]}
                      onPress={() => handleCancelReservation(item.id)}
                      disabled={cancelingReservationId === item.id}
                    >
                      <View style={styles.cancelContent}>
                        <MaterialIcons
                          name="cancel"
                          size={14}
                          color="#DC2626"
                        />
                        <Text style={styles.cancelButtonText}>
                          {cancelingReservationId === item.id
                            ? "Cancelando..."
                            : "Cancelar"}
                        </Text>
                      </View>
                    </Pressable>
                  </View>
                </View>
              ))
            )}
          </View>
        ) : null}

        {/* seccion historial */}
        {activeTab === "history" ? (
          <View style={styles.section}>
            <View style={styles.sectionHeader}>
              <Text style={styles.sectionTitle}>Historial</Text>
            </View>

            {historyReservations.length === 0 ? (
              <View style={styles.emptyCard}>
                <Text style={styles.emptyTitle}>No tienes historial</Text>
                <Text style={styles.emptyText}>
                  Aquí verás tus reservas completadas o canceladas.
                </Text>
              </View>
            ) : (
              historyReservations.map((item) => (
                <View key={item.id} style={styles.card}>
                  {/* cabecera de la tarjeta */}
                  <View style={styles.cardHeader}>
                    <View style={styles.cardHeaderLeft}>
                      <View style={styles.cardIconWrap}>
                        <MaterialIcons
                          name="business"
                          size={22}
                          color={colors.primary}
                        />
                      </View>

                      <View style={styles.cardTitleBlock}>
                        <Text style={styles.cardTitle}>{item.officeName}</Text>
                        <Text style={styles.cardSubtitle}>
                          Reserva finalizada
                        </Text>
                      </View>
                    </View>

                    <View
                      style={[
                        styles.statusBadge,
                        item.status === "completed"
                          ? styles.statusCompleted
                          : styles.statusCancelled,
                      ]}
                    >
                      <Text
                        style={[
                          styles.statusText,
                          item.status === "completed"
                            ? styles.statusTextCompleted
                            : styles.statusTextCancelled,
                        ]}
                      >
                        {item.status === "completed"
                          ? "Completada"
                          : "Cancelada"}
                      </Text>
                    </View>
                  </View>

                  {/* detalles de historial */}
                  <View style={styles.detailsList}>
                    <View style={styles.detailRow}>
                      <MaterialIcons
                        name="calendar-month"
                        size={16}
                        color={colors.textSecondary}
                      />
                      <Text style={styles.detailText}>{item.date}</Text>
                    </View>

                    <View style={styles.detailRow}>
                      <MaterialIcons
                        name="schedule"
                        size={16}
                        color={colors.textSecondary}
                      />
                      <Text style={styles.detailText}>
                        {item.startTime} - {item.endTime}
                      </Text>
                    </View>

                    <View style={styles.detailRow}>
                      <MaterialIcons
                        name="login"
                        size={16}
                        color={colors.textSecondary}
                      />
                      <Text style={styles.detailText}>
                        {item.checkInAt
                          ? `Llegada registrada: ${formatCheckInAt(item.checkInAt)}`
                          : "Llegada no registrada"}
                      </Text>
                    </View>
                  </View>
                </View>
              ))
            )}
          </View>
        ) : null}
      </ScrollView>
    </View>
  );
}

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",
  },
});