import React, { useEffect, useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { useKindeAuth } from "@kinde-oss/kinde-auth-react";
import { ArrowLeft, AlertCircle } from "lucide-react";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "../components/ui/table";
import Button from "../components/ui/button";
interface ProximalSelection {
id: string;
startTime: number;
endTime: number;
description: string | null;
timestamp: string;
distanceMeters: number;
timeOffsetMinutes: number;
cluster: {
id: string;
name: string;
location: {
id: string;
name: string;
latitude: number;
longitude: number;
};
};
file: {
id: string;
fileName: string;
path: string;
duration: number;
};
}
interface GroundZeroSelection {
id: string;
startTime: number;
endTime: number;
description: string | null;
timestamp: string;
cluster: {
id: string;
name: string;
location: {
id: string;
name: string;
latitude: number;
longitude: number;
};
};
file: {
id: string;
fileName: string;
path: string;
duration: number;
};
}
interface ProximalSelectionsData {
groundZero: GroundZeroSelection;
proximalSelections: ProximalSelection[];
timeWindow: {
start: string;
end: string;
durationMinutes: number;
};
}
export const ProximalSelectionsPage: React.FC = () => {
const { selectionId } = useParams<{ selectionId: string }>();
const navigate = useNavigate();
const { getAccessToken } = useKindeAuth();
const [data, setData] = useState<ProximalSelectionsData | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const fetchProximalSelections = async () => {
if (!selectionId) return;
try {
setLoading(true);
setError(null);
const accessToken = await getAccessToken();
const response = await fetch(`/api/selections/${selectionId}/proximal`, {
headers: { Authorization: `Bearer ${accessToken}` },
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || `HTTP ${response.status}`);
}
const result = await response.json();
setData(result.data);
} catch (err) {
console.error("Failed to fetch proximal selections:", err);
setError(err instanceof Error ? err.message : "Unknown error");
} finally {
setLoading(false);
}
};
void fetchProximalSelections();
}, [selectionId, getAccessToken]);
const formatDistance = (meters: number): string => {
if (meters === 0) return "0 m";
if (meters < 1000) return `${meters} m`;
return `${(meters / 1000).toFixed(1)} km`;
};
const formatTimeOffset = (minutes: number): string => {
if (minutes === 0) return "0 min";
const sign = minutes > 0 ? "+" : "";
return `${sign}${minutes} min`;
};
const formatTime = (seconds: number): string => {
const minutes = Math.floor(seconds / 60);
const secs = Math.floor(seconds % 60);
return `${minutes}:${secs.toString().padStart(2, "0")}`;
};
const handleBack = () => {
navigate(-1);
};
if (!selectionId) {
return (
<div className="p-4 bg-red-50 text-red-700 rounded-md">
<p>Missing selection ID parameter.</p>
</div>
);
}
if (loading) {
return (
<div className="p-6">
<div className="flex items-center gap-2 mb-6">
<Button onClick={handleBack} variant="outline" size="sm">
<ArrowLeft className="h-4 w-4 mr-2" />
Back
</Button>
<h1 className="text-xl font-semibold">Proximal Selections</h1>
</div>
<div className="text-center py-8 text-gray-500">
Loading proximal selections...
</div>
</div>
);
}
if (error) {
return (
<div className="p-6">
<div className="flex items-center gap-2 mb-6">
<Button onClick={handleBack} variant="outline" size="sm">
<ArrowLeft className="h-4 w-4 mr-2" />
Back
</Button>
<h1 className="text-xl font-semibold">Proximal Selections</h1>
</div>
<div className="flex items-center gap-2 p-4 bg-red-50 text-red-700 rounded-md">
<AlertCircle className="h-4 w-4" />
<p>Error loading proximal selections: {error}</p>
</div>
</div>
);
}
if (!data) {
return (
<div className="p-6">
<div className="flex items-center gap-2 mb-6">
<Button onClick={handleBack} variant="outline" size="sm">
<ArrowLeft className="h-4 w-4 mr-2" />
Back
</Button>
<h1 className="text-xl font-semibold">Proximal Selections</h1>
</div>
<div className="text-center py-8 text-gray-500">
No data available.
</div>
</div>
);
}
return (
<div className="p-6">
<div className="flex items-center gap-2 mb-6">
<Button onClick={handleBack} variant="outline" size="sm">
<ArrowLeft className="h-4 w-4 mr-2" />
Back
</Button>
<h1 className="text-xl font-semibold">Proximal Selections</h1>
</div>
{/* Ground Zero Info */}
<div className="mb-6 p-4 bg-gray-50 rounded-lg">
<h2 className="text-lg font-medium mb-2">Ground Zero Selection</h2>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
<div>
<span className="font-medium">File:</span> {data.groundZero.file.fileName}
</div>
<div>
<span className="font-medium">Location:</span> {data.groundZero.cluster.location.name}
</div>
<div>
<span className="font-medium">Cluster:</span> {data.groundZero.cluster.name}
</div>
<div>
<span className="font-medium">Time:</span> {formatTime(data.groundZero.startTime)} - {formatTime(data.groundZero.endTime)}
</div>
<div>
<span className="font-medium">Coordinates:</span> {data.groundZero.cluster.location.latitude.toFixed(6)}, {data.groundZero.cluster.location.longitude.toFixed(6)}
</div>
<div>
<span className="font-medium">Timestamp:</span> {new Date(data.groundZero.timestamp).toLocaleString()}
</div>
</div>
{data.groundZero.description && (
<div className="mt-2 text-sm">
<span className="font-medium">Description:</span> {data.groundZero.description}
</div>
)}
</div>
{/* Time Window Info */}
<div className="mb-6 p-3 bg-blue-50 rounded-lg">
<p className="text-sm text-blue-800">
Showing selections within ±30 minutes ({new Date(data.timeWindow.start).toLocaleString()} - {new Date(data.timeWindow.end).toLocaleString()})
</p>
<p className="text-sm text-blue-600 mt-1">
Found {data.proximalSelections.length} selections
</p>
</div>
{/* Proximal Selections Table */}
{data.proximalSelections.length > 0 ? (
<div className="w-full overflow-x-auto">
<Table>
<TableHeader className="bg-gray-50">
<TableRow>
<TableHead className="py-3 font-bold text-sm uppercase">Distance</TableHead>
<TableHead className="py-3 font-bold text-sm uppercase">Time Offset</TableHead>
<TableHead className="py-3 font-bold text-sm uppercase">Location</TableHead>
<TableHead className="py-3 font-bold text-sm uppercase">Cluster</TableHead>
<TableHead className="py-3 font-bold text-sm uppercase">File</TableHead>
<TableHead className="py-3 font-bold text-sm uppercase">Start Time</TableHead>
<TableHead className="py-3 font-bold text-sm uppercase">End Time</TableHead>
<TableHead className="py-3 font-bold text-sm uppercase">Description</TableHead>
<TableHead className="py-3 font-bold text-sm uppercase">Timestamp</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{data.proximalSelections.map((selection) => (
<TableRow
key={selection.id}
className={`hover:bg-gray-50 ${
selection.id === data.groundZero.id ? "bg-gray-100" : ""
}`}
>
<TableCell className="font-medium text-right">
{formatDistance(selection.distanceMeters)}
</TableCell>
<TableCell className="text-center">
{formatTimeOffset(selection.timeOffsetMinutes)}
</TableCell>
<TableCell className="whitespace-normal break-words">
{selection.cluster.location.name}
</TableCell>
<TableCell className="whitespace-normal break-words">
{selection.cluster.name}
</TableCell>
<TableCell className="whitespace-normal break-words">
{selection.file.fileName}
</TableCell>
<TableCell>{formatTime(selection.startTime)}</TableCell>
<TableCell>{formatTime(selection.endTime)}</TableCell>
<TableCell className="whitespace-normal break-words">
{selection.description || "-"}
</TableCell>
<TableCell className="whitespace-normal break-words text-sm text-gray-500">
{new Date(selection.timestamp).toLocaleString()}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
) : (
<div className="text-center py-8 text-gray-500">
No proximal selections found within the time window.
</div>
)}
</div>
);
};