aboutsummaryrefslogtreecommitdiff
path: root/src/frontend/app/routes/estimates-$id.tsx
blob: b5ae91a0b9662887edf5eb2d08ea1aca31af32a8 (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
import { type JSX, useEffect, useState } from "react";
import { useParams, Link } from "react-router";
import StopDataProvider from "../data/StopDataProvider";
import { Star, Edit2, ExternalLink } from "lucide-react";
import "./estimates-$id.css";
import { RegularTable } from "../components/RegularTable";
import { useApp } from "../AppContext";
import { GroupedTable } from "../components/GroupedTable";
import { useTranslation } from "react-i18next";
import { TimetableTable, type TimetableEntry } from "../components/TimetableTable";

export interface StopDetails {
  stop: {
    id: number;
    name: string;
    latitude: number;
    longitude: number;
  };
  estimates: {
    line: string;
    route: string;
    minutes: number;
    meters: number;
  }[];
}

const loadData = async (stopId: string) => {
  const resp = await fetch(`/api/GetStopEstimates?id=${stopId}`, {
    headers: {
      Accept: "application/json",
    },
  });
  return await resp.json();
};

const loadTimetableData = async (stopId: string) => {
  const today = new Date().toISOString().split('T')[0]; // YYYY-MM-DD format
  try {
    const resp = await fetch(`/api/GetStopTimetable?date=${today}&stopId=${stopId}`, {
      headers: {
        Accept: "application/json",
      },
    });
    if (!resp.ok) {
      throw new Error(`HTTP error! status: ${resp.status}`);
    }
    return await resp.json();
  } catch (error) {
    console.error('Error loading timetable data:', error);
    return [];
  }
};

export default function Estimates() {
  const { t } = useTranslation();
  const params = useParams();
  const stopIdNum = parseInt(params.id ?? "");
  const [customName, setCustomName] = useState<string | undefined>(undefined);
  const [data, setData] = useState<StopDetails | null>(null);
  const [dataDate, setDataDate] = useState<Date | null>(null);
  const [favourited, setFavourited] = useState(false);
  const [timetableData, setTimetableData] = useState<TimetableEntry[]>([]);
  const { tableStyle } = useApp();

  useEffect(() => {
    // Load real-time estimates
    loadData(params.id!).then((body: StopDetails) => {
      setData(body);
      setDataDate(new Date());
      setCustomName(StopDataProvider.getCustomName(stopIdNum));
    });

    // Load timetable data
    loadTimetableData(params.id!).then((timetableBody: TimetableEntry[]) => {
      setTimetableData(timetableBody);
    });

    StopDataProvider.pushRecent(parseInt(params.id ?? ""));

    setFavourited(StopDataProvider.isFavourite(parseInt(params.id ?? "")));
  }, [params.id]);

  const toggleFavourite = () => {
    if (favourited) {
      StopDataProvider.removeFavourite(stopIdNum);
      setFavourited(false);
    } else {
      StopDataProvider.addFavourite(stopIdNum);
      setFavourited(true);
    }
  };

  const handleRename = () => {
    const current = customName ?? data?.stop.name;
    const input = window.prompt("Custom name for this stop:", current);
    if (input === null) return; // cancelled
    const trimmed = input.trim();
    if (trimmed === "") {
      StopDataProvider.removeCustomName(stopIdNum);
      setCustomName(undefined);
    } else {
      StopDataProvider.setCustomName(stopIdNum, trimmed);
      setCustomName(trimmed);
    }
  };

  if (data === null)
    return <h1 className="page-title">{t("common.loading")}</h1>;

  return (
    <div className="page-container">
      <div className="estimates-header">
        <h1 className="page-title">
          <Star
            className={`star-icon ${favourited ? "active" : ""}`}
            onClick={toggleFavourite}
          />
          <Edit2 className="edit-icon" onClick={handleRename} />
          {customName ?? data.stop.name}{" "}
          <span className="estimates-stop-id">({data.stop.id})</span>
        </h1>
      </div>

      <div className="table-responsive">
        {tableStyle === "grouped" ? (
          <GroupedTable data={data} dataDate={dataDate} />
        ) : (
          <RegularTable data={data} dataDate={dataDate} />
        )}
      </div>

      <div className="timetable-section">
        <TimetableTable 
          data={timetableData}
          currentTime={new Date().toTimeString().slice(0, 8)} // HH:MM:SS
        />
        
        {timetableData.length > 0 && (
          <div className="timetable-actions">
            <Link 
              to={`/timetable/${params.id}`} 
              className="view-all-link"
            >
              <ExternalLink className="external-icon" />
              {t("timetable.viewAll", "Ver todos los horarios")}
            </Link>
          </div>
        )}
      </div>
    </div>
  );
}