"use client"; import { useEffect, useState } from "react"; import { useParams, useNavigate } from "react-router-dom"; import apiService from "../services/apiService"; import type { MigrantProfile } from "../types/migrant"; import MigrantProfileComponent from "../components/MigrantProfileComponent"; import { Alert, AlertTitle, AlertDescription } from "@/components/ui/alert"; import { AlertCircle, Loader2 } from "lucide-react"; import { Button } from "@/components/ui/button"; // Helper function to calculate age at migration const calculateAgeAtMigration = (birthDate: string | null | undefined, migrationDate: string | null | undefined): number => { if (!birthDate || !migrationDate) return 0; try { const normalizedBirthDate = birthDate.includes('.') ? birthDate.split('.')[0] + 'Z' : birthDate; const normalizedMigrationDate = migrationDate.includes('.') ? migrationDate.split('.')[0] + 'Z' : migrationDate; const birthYear = new Date(normalizedBirthDate).getFullYear(); const migrationYear = new Date(normalizedMigrationDate).getFullYear(); // Simple year difference calculation const age = migrationYear - birthYear; return age >= 0 ? age : 0; } catch (error) { console.error(`Error calculating age: birth=${birthDate}, migration=${migrationDate}`, error); return 0; } }; const MigrantProfilePage = () => { const { id } = useParams<{ id: string }>(); const navigate = useNavigate(); const [migrant, setMigrant] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [retryCount, setRetryCount] = useState(0); // Fetch migrant data when component mounts or ID changes useEffect(() => { const fetchMigrantData = async () => { // Reset state when ID changes setLoading(true); setMigrant(null); setError(null); if (!id) { setError('Missing migrant ID'); setLoading(false); return; } try { // Fetch migrant data from the backend using apiService const data = await apiService.getRecordById(id); if (data) { // Data successfully retrieved - convert API data to MigrantProfile const migrantProfile: MigrantProfile = { id: data.person_id || id, firstName: data.christian_name || '', lastName: data.surname || '', middleName: '', birthDate: data.date_of_birth || '', birthPlace: data.place_of_birth || '', ageAtMigration: calculateAgeAtMigration(data.date_of_birth, data.migration?.date_of_arrival_nt), yearOfArrival: data.migration?.date_of_arrival_nt ? new Date(data.migration.date_of_arrival_nt).getFullYear() : 0, regionOfOrigin: data.place_of_birth || 'Unknown', settlementLocation: data.residence?.town_or_city || 'Unknown', occupation: data.occupation || 'Unknown', deathDate: data.date_of_death || '', deathPlace: data.residence?.home_at_death || '', mainPhoto: '', // No photo URL in the API response biography: data.additional_notes || '', photos: [], relatedMigrants: [] }; setMigrant(migrantProfile); setError(null); } else { // No data found for this ID setMigrant(null); setError(`No migrant found with ID: ${id}`); } } catch (error: any) { // Handle API errors const errorMessage = error.response?.data?.message || error.message || 'An unexpected error occurred'; console.error('Error fetching migrant:', errorMessage); setError(`Failed to load migrant data: ${errorMessage}`); } finally { setLoading(false); } }; fetchMigrantData(); }, [id, retryCount]); // retryCount allows manual retries // Handle retry button click const handleRetry = () => { setRetryCount(prev => prev + 1); }; // Loading state if (loading) { return (

Loading migrant profile...

Retrieving data from the database

); } // Error state if (error) { // Check if the error is specifically about not finding a migrant const isNotFoundError = error.includes('No migrant found'); return (
{isNotFoundError ? "Migrant Not Found" : "Error"} {error}
{isNotFoundError && (

The migrant profile you're looking for could not be found in our database.

This might be because:

  • The ID provided is incorrect
  • The record has been removed from the database
  • The record hasn't been added to the database yet
)}
{!isNotFoundError && ( )}
); } // No data state (should be caught by error state, but just in case) if (!migrant) { return (

Migrant Profile Not Found

The migrant profile you're looking for could not be found.

); } // Render migrant profile when data is loaded successfully return ; }; export default MigrantProfilePage;