import { useKindeAuth } from "@kinde-oss/kinde-auth-react";
import React, { useEffect, useState } from "react";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { Button } from "./ui/button";
interface FileMetadata {
noiseType?: string[];
noiseLevel?: string;
[key: string]: unknown;
}
interface MothMetadata {
gain: string | null;
batteryV: number | null;
tempC: number | null;
}
interface Species {
id: string;
label: string;
ebirdCode: string | null;
description: string | null;
}
interface File {
id: string;
fileName: string;
path: string | null;
timestampLocal: string;
duration: number;
sampleRate: number;
locationId: string;
clusterId: string;
description: string | null;
maybeSolarNight: boolean | null;
maybeCivilNight: boolean | null;
moonPhase: number | null;
metadata: FileMetadata | null;
mothMetadata?: MothMetadata | null;
species?: Species[];
}
interface PaginationMetadata {
currentPage: number;
pageSize: number;
totalPages: number;
totalItems: number;
hasNextPage: boolean;
hasPreviousPage: boolean;
}
interface FilesFilters {
datasetId: string;
speciesId: string;
solarNight: boolean | null;
civilNight: boolean | null;
}
interface FilesResponse {
data: File[];
pagination: PaginationMetadata;
filters?: FilesFilters;
}
type NightFilter = 'none' | 'solarNight' | 'solarDay' | 'civilNight' | 'civilDay';
// Species data type for the dropdown
interface SpeciesOption {
id: string;
label: string;
}
// Define a component for just the filter controls
export const SelectionsFilter: React.FC<{
datasetId: string;
onFilterChange: (filter: NightFilter) => void;
currentFilter: NightFilter;
onSpeciesFilterChange: (speciesId: string | null) => void;
currentSpeciesId: string | null;
speciesOptions: SpeciesOption[];
totalFiles?: number;
}> = ({
currentFilter,
onFilterChange,
currentSpeciesId,
onSpeciesFilterChange,
speciesOptions,
totalFiles
}) => {
return (
<div className="flex flex-wrap items-center gap-4">
<div className="flex items-center">
<select
id="nightFilter"
value={currentFilter}
onChange={(e) => onFilterChange(e.target.value as NightFilter)}
className="rounded-md border border-gray-300 bg-white py-1 px-3 text-sm shadow-sm focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
>
<option value="none">No Time Filter</option>
<option value="solarNight">Solar night</option>
<option value="solarDay">Solar day</option>
<option value="civilNight">Civil night</option>
<option value="civilDay">Civil day</option>
</select>
</div>
{speciesOptions.length > 0 && (
<div className="flex items-center">
<select
id="speciesFilter"
value={currentSpeciesId || ''}
onChange={(e) => onSpeciesFilterChange(e.target.value || null)}
className="rounded-md border border-gray-300 bg-white py-1 px-3 text-sm shadow-sm focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
>
{speciesOptions.map(species => (
<option key={species.id} value={species.id}>
{species.label}
</option>
))}
</select>
</div>
)}
{totalFiles !== undefined && (
<div className="text-gray-600 text-sm">
{totalFiles} files
</div>
)}
</div>
);
};
interface SelectionsProps {
datasetId: string;
datasetName?: string;
speciesId?: string;
hideHeaderInfo?: boolean;
nightFilter?: NightFilter;
}
const Selections: React.FC<SelectionsProps> = ({
datasetId,
datasetName,
speciesId: initialSpeciesId,
hideHeaderInfo = false,
nightFilter: externalNightFilter
}) => {
React.useEffect(() => {
if (process.env.NODE_ENV === 'development') {
console.log('Selections component props:', { datasetId, datasetName, speciesId: initialSpeciesId, hideHeaderInfo });
}
}, [datasetId, datasetName, initialSpeciesId, hideHeaderInfo]);
const { isAuthenticated, isLoading: authLoading, getAccessToken } = useKindeAuth();
const [files, setFiles] = useState<File[]>([]);
const [pagination, setPagination] = useState<PaginationMetadata | null>(null);
const [loading, setLoading] = useState<boolean>(true);
const [error, setError] = useState<string | null>(null);
const [currentPage, setCurrentPage] = useState<number>(1);
const [hasMetadata, setHasMetadata] = useState<boolean>(false);
const [hasMothMetadata, setHasMothMetadata] = useState<boolean>(false);
const [nightFilter, setNightFilter] = useState<NightFilter>(externalNightFilter || 'none');
const [speciesFilter, setSpeciesFilter] = useState<string | null>(initialSpeciesId || null);
const [speciesOptions, setSpeciesOptions] = useState<SpeciesOption[]>([]);
const [hasSpecies, setHasSpecies] = useState<boolean>(false);
const [, setLoadingSpecies] = useState<boolean>(true);
const formatDuration = (durationSec: number): string => {
const minutes = Math.floor(durationSec / 60);
const seconds = Math.floor(durationSec % 60);
return `${minutes}:${seconds.toString().padStart(2, '0')}`;
};
const formatMoonPhase = (phase: number | null | undefined): string => {
if (phase === null || phase === undefined) return "—";
try {
return Number(phase).toFixed(2);
} catch {
return "—";
}
};
const formatBatteryVoltage = (volts: number | null | undefined): string => {
if (volts === null || volts === undefined) return "—";
try {
return Number(volts).toFixed(1) + 'V';
} catch {
return "—";
}
};
const formatTemperature = (temp: number | null | undefined): string => {
if (temp === null || temp === undefined) return "—";
try {
return Number(temp).toFixed(1) + '°C';
} catch {
return "—";
}
};
const handlePageChange = (newPage: number) => {
if (newPage >= 1 && (!pagination || newPage <= pagination.totalPages)) {
setCurrentPage(newPage);
}
};
const handleSpeciesFilterChange = (newSpeciesId: string | null) => {
setSpeciesFilter(newSpeciesId);
// Reset to first page when changing filters
setCurrentPage(1);
};
useEffect(() => {
// Reset state when dataset changes
setFiles([]);
setPagination(null);
setLoading(true);
setError(null);
const fetchFiles = async () => {
if (!isAuthenticated || !datasetId || !speciesFilter) {
if (!authLoading) {
setLoading(false);
}
return;
}
try {
const accessToken = await getAccessToken();
// Build URL with required parameters
let url = `/api/selections?datasetId=${encodeURIComponent(datasetId)}&speciesId=${encodeURIComponent(speciesFilter)}&page=${currentPage}&pageSize=100`;
// Add night filters
switch (nightFilter) {
case 'solarNight':
url += '&solarNight=true';
break;
case 'solarDay':
url += '&solarNight=false';
break;
case 'civilNight':
url += '&civilNight=true';
break;
case 'civilDay':
url += '&civilNight=false';
break;
// 'none' doesn't add any filter parameters
}
const response = await fetch(url, {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
if (!response.ok) {
throw new Error(`Server error: ${response.status}`);
}
const data = await response.json() as FilesResponse;
if (!data.data || !Array.isArray(data.data) || !data.pagination) {
throw new Error("Invalid response format");
}
// Check if valid metadata is present in any file
const validMetadata = data.data.some(file => {
if (!file.metadata) return false;
try {
const meta = typeof file.metadata === 'string'
? JSON.parse(file.metadata)
: file.metadata;
return meta && typeof meta === 'object' && Object.keys(meta).length > 0;
} catch {
return false;
}
});
// Check if any files have moth metadata
const validMothMetadata = data.data.some(file =>
file.mothMetadata &&
(file.mothMetadata.gain !== null ||
file.mothMetadata.batteryV !== null ||
file.mothMetadata.tempC !== null)
);
// Check if any files have species information
const validSpeciesData = data.data.some(file =>
file.species && file.species.length > 0
);
setHasMetadata(validMetadata);
setHasMothMetadata(validMothMetadata);
setHasSpecies(validSpeciesData || speciesOptions.length > 0);
setFiles(data.data);
setPagination(data.pagination);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : "Failed to fetch files";
setError(errorMessage);
} finally {
setLoading(false);
}
};
if (isAuthenticated && !authLoading && speciesFilter) {
fetchFiles();
} else if (isAuthenticated && !authLoading && !speciesFilter) {
// If no species filter is set, don't make a fetch request but clear loading state
setLoading(false);
}
}, [isAuthenticated, authLoading, getAccessToken, datasetId, speciesFilter, currentPage, nightFilter, speciesOptions.length]);
// Update internal state when external filter changes
useEffect(() => {
if (externalNightFilter !== undefined) {
setNightFilter(externalNightFilter);
}
}, [externalNightFilter]);
// Update species filter when initialSpeciesId changes
useEffect(() => {
setSpeciesFilter(initialSpeciesId || null);
}, [initialSpeciesId]);
// Fetch species for the dataset to populate the species filter dropdown
useEffect(() => {
setLoadingSpecies(true);
setSpeciesOptions([]);
const fetchSpecies = async () => {
if (!isAuthenticated || !datasetId) {
setLoadingSpecies(false);
setSpeciesOptions([]);
return;
}
try {
const accessToken = await getAccessToken();
const url = `/api/species?datasetId=${encodeURIComponent(datasetId)}`;
const response = await fetch(url, {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
if (!response.ok) {
throw new Error(`Server error: ${response.status}`);
}
const data = await response.json() as { data: SpeciesOption[] };
if (!data.data || !Array.isArray(data.data)) {
throw new Error("Invalid response format");
}
setSpeciesOptions(data.data);
setHasSpecies(data.data.length > 0);
} catch (err) {
console.error("Error fetching species:", err);
// Don't show error for species, just hide the filter
setSpeciesOptions([]);
} finally {
setLoadingSpecies(false);
}
};
if (isAuthenticated && !authLoading) {
fetchSpecies();
}
}, [isAuthenticated, authLoading, getAccessToken, datasetId]);
return (
<div className="card p-6 bg-white shadow-sm rounded-lg">
{/* Header removed as requested */}
{/* Filter controls - always show filters when we have data to filter */}
{!loading && !error && (
<div className="mb-4">
<SelectionsFilter
datasetId={datasetId}
currentFilter={nightFilter}
onFilterChange={setNightFilter}
currentSpeciesId={speciesFilter}
onSpeciesFilterChange={handleSpeciesFilterChange}
speciesOptions={speciesOptions}
totalFiles={pagination?.totalItems}
/>
</div>
)}
{/* Select species prompt when no species is selected */}
{!loading && !error && !speciesFilter && speciesOptions.length > 0 && (
<div className="py-4 text-center text-gray-600 bg-gray-50 rounded-md">
Please select a species to view files
</div>
)}
{loading && <div className="py-4 text-center text-gray-500">Loading files...</div>}
{error && (
<div className="p-4 bg-red-50 text-red-700 rounded-md mb-4">
<p className="font-medium">Error loading files</p>
<p className="text-sm mt-1">{error}</p>
</div>
)}
{!loading && !error && speciesFilter && (
<>
<div className="w-full overflow-visible">
<Table>
<TableHeader className="bg-muted">
<TableRow className="border-b-2 border-primary/20">
<TableHead className="w-[240px] py-3 font-bold text-sm uppercase">File</TableHead>
{hasSpecies && (
<TableHead className="py-3 font-bold text-sm uppercase">Species</TableHead>
)}
<TableHead className="py-3 font-bold text-sm uppercase">Duration</TableHead>
{hasMothMetadata && (
<>
<TableHead className="py-3 font-bold text-sm uppercase">Gain</TableHead>
<TableHead className="py-3 font-bold text-sm uppercase">Battery</TableHead>
<TableHead className="py-3 font-bold text-sm uppercase">Temp</TableHead>
</>
)}
<TableHead className="py-3 font-bold text-sm uppercase">Moon Phase</TableHead>
{hasMetadata && (
<TableHead className="py-3 font-bold text-sm uppercase">Metadata</TableHead>
)}
</TableRow>
</TableHeader>
<TableBody>
{files.length > 0 ? (
files.map((file) => (
<TableRow key={file.id}>
<TableCell className="font-medium whitespace-normal break-words">{file.fileName}</TableCell>
{hasSpecies && (
<TableCell className="whitespace-normal break-words">
{file.species && file.species.length > 0 ? (
<div className="flex flex-wrap gap-1">
{file.species.map(species => (
<div
key={species.id}
className="inline-block px-3 py-1 rounded-full text-xs font-medium bg-stone-200 text-stone-800 text-center whitespace-nowrap overflow-hidden text-ellipsis"
style={{ minWidth: '80px', maxWidth: '150px' }}
title={species.label} // Show full name on hover
>
{species.label}
</div>
))}
</div>
) : "—"}
</TableCell>
)}
<TableCell className="whitespace-normal break-words">{formatDuration(Number(file.duration))}</TableCell>
{hasMothMetadata && (
<>
<TableCell className="whitespace-normal break-words">
{file.mothMetadata?.gain || "—"}
</TableCell>
<TableCell className="whitespace-normal break-words">
{formatBatteryVoltage(file.mothMetadata?.batteryV)}
</TableCell>
<TableCell className="whitespace-normal break-words">
{formatTemperature(file.mothMetadata?.tempC)}
</TableCell>
</>
)}
<TableCell className="whitespace-normal break-words">
{formatMoonPhase(file.moonPhase)}
</TableCell>
{hasMetadata && (
<TableCell className="whitespace-normal break-words">
{file.metadata ? (
(() => {
try {
// Parse metadata if it's a string
const metaObj = typeof file.metadata === 'string'
? JSON.parse(file.metadata)
: file.metadata;
// Format as key-value pairs
if (typeof metaObj === 'object' && metaObj !== null) {
const pairs = Object.entries(metaObj).map(([key, value]) => {
// Handle arrays or objects as values
let displayValue = value;
if (Array.isArray(value)) {
// Remove quotes and brackets from array string
displayValue = value.join(', ').replace(/[[\]"]*/g, '');
} else if (typeof value === 'string') {
// Remove quotes from string values
displayValue = value.replace(/^"|"$/g, '');
}
return `${key}: ${displayValue}`;
});
return pairs.join(', ');
}
return JSON.stringify(metaObj);
} catch (e) {
console.error("Error formatting metadata:", e);
return typeof file.metadata === 'string'
? (file.metadata as string).substring(0, 50)
: "Invalid metadata";
}
})()
) : "—"}
</TableCell>
)}
</TableRow>
))
) : (
<TableRow>
<TableCell
colSpan={
// Calculate total columns based on optional columns
3 + // File, Duration, Moon Phase (always present)
(hasSpecies ? 1 : 0) +
(hasMothMetadata ? 3 : 0) +
(hasMetadata ? 1 : 0)
}
className="text-center py-8"
>
<div className="text-gray-500">
No files found with the selected filters
</div>
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
{pagination && pagination.totalPages > 1 && files.length > 0 && (
<div className="flex justify-center items-center mt-6">
<nav className="flex items-center gap-1" aria-label="Pagination">
{/* First page button */}
<Button
variant="outline"
size="icon"
className="h-8 w-8 rounded-md"
onClick={() => handlePageChange(1)}
disabled={currentPage === 1}
aria-label="First page"
>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<polyline points="11 17 6 12 11 7"></polyline>
<polyline points="18 17 13 12 18 7"></polyline>
</svg>
</Button>
{/* Previous page button */}
<Button
variant="outline"
size="icon"
className="h-8 w-8 rounded-md"
onClick={() => handlePageChange(currentPage - 1)}
disabled={currentPage === 1}
aria-label="Previous page"
>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<polyline points="15 18 9 12 15 6"></polyline>
</svg>
</Button>
{/* Page number buttons */}
{(() => {
const totalPages = pagination.totalPages;
const current = currentPage;
const pages = [];
// Always show first page
if (current > 3) {
pages.push(
<Button
key="page-1"
variant={current === 1 ? "default" : "outline"}
size="icon"
className="h-8 w-8 rounded-md"
onClick={() => handlePageChange(1)}
>
1
</Button>
);
// Add ellipsis if not showing page 2
if (current > 4) {
pages.push(
<span key="ellipsis1" className="px-1">…</span>
);
}
}
// Show current page and surrounding pages
const startPage = Math.max(1, current - 1);
const endPage = Math.min(totalPages, current + 1);
for (let i = startPage; i <= endPage; i++) {
if (i === 1 || i === totalPages) continue; // Skip first and last pages as they're handled separately
pages.push(
<Button
key={`page-${i}`}
variant={current === i ? "default" : "outline"}
size="icon"
className="h-8 w-8 rounded-md"
onClick={() => handlePageChange(i)}
>
{i}
</Button>
);
}
// Add intermediate points
const checkpoints = [10, 20, 30, 40];
if (totalPages > 5) {
for (const checkpoint of checkpoints) {
if (checkpoint > current + 2 && checkpoint < totalPages - 2) {
// Only insert checkpoint if it's not close to what we already display
if (!pages.some(p => p.key === `page-${checkpoint}`)) {
pages.push(
<Button
key={`page-${checkpoint}`}
variant="outline"
size="icon"
className="h-8 w-8 rounded-md"
onClick={() => handlePageChange(checkpoint)}
>
{checkpoint}
</Button>
);
// Insert only one checkpoint button
break;
}
}
}
}
// Add ellipsis if needed
if (current < totalPages - 3) {
pages.push(
<span key="ellipsis2" className="px-1">…</span>
);
}
// Always show last page
if (totalPages > 1) {
pages.push(
<Button
key={`page-${totalPages}`}
variant={current === totalPages ? "default" : "outline"}
size="icon"
className="h-8 w-8 rounded-md"
onClick={() => handlePageChange(totalPages)}
>
{totalPages}
</Button>
);
}
return pages;
})()}
{/* Next page button */}
<Button
variant="outline"
size="icon"
className="h-8 w-8 rounded-md"
onClick={() => handlePageChange(currentPage + 1)}
disabled={currentPage === pagination.totalPages}
aria-label="Next page"
>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<polyline points="9 18 15 12 9 6"></polyline>
</svg>
</Button>
{/* Last page button */}
<Button
variant="outline"
size="icon"
className="h-8 w-8 rounded-md"
onClick={() => handlePageChange(pagination.totalPages)}
disabled={currentPage === pagination.totalPages}
aria-label="Last page"
>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<polyline points="13 17 18 12 13 7"></polyline>
<polyline points="6 17 11 12 6 7"></polyline>
</svg>
</Button>
</nav>
</div>
)}
</>
)}
{/* No species available message */}
{!loading && !error && speciesOptions.length === 0 && (
<div className="p-4 bg-yellow-50 text-yellow-800 rounded-md">
<p className="font-medium">No species found for this dataset</p>
<p className="text-sm mt-1">Try selecting a different dataset or adding species to this dataset</p>
</div>
)}
</div>
);
};
export default Selections;