import React, { useState, useEffect, useMemo } from 'react'; import { Activity, Truck, HeartPulse, Video, ShieldCheck, Database, Settings, Users as UsersIcon, RefreshCw, Zap, Navigation } from 'lucide-react'; import { StatCard, Card } from '../components/Common'; import { AreaChart, Area, Tooltip, ResponsiveContainer, PieChart, Pie, Cell } from 'recharts'; import { motion, AnimatePresence } from 'framer-motion'; import { incidentsApi } from '../api/incidents'; import { authApi } from '../api/auth'; import type { Incident } from '../api/types'; // --- LIVE INCIDENT MAP COMPONENT --- const LiveIncidentMap: React.FC<{ incidents: Incident[] }> = ({ incidents }) => { const [isMapReady, setIsMapReady] = React.useState(false); const mapRef = React.useRef(null); const containerRef = React.useRef(null); const markersRef = React.useRef<{ [key: string]: any }>({}); const [L, setL] = React.useState(null); React.useEffect(() => { if (typeof window === 'undefined') return; // Ensure Leaflet assets are loaded if (!document.getElementById('leaflet-style')) { const link = document.createElement('link'); link.id = 'leaflet-style'; link.rel = 'stylesheet'; link.href = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css'; document.head.appendChild(link); } const initMap = (leaflet: any) => { if (!containerRef.current || mapRef.current) return; // Defensive: Clear container if Leaflet previously left a trace but we lost the ref if ((containerRef.current as any)._leaflet_id) { containerRef.current.innerHTML = ''; delete (containerRef.current as any)._leaflet_id; } const m = leaflet.map(containerRef.current, { zoomControl: false, attributionControl: false }).setView([12.9716, 77.5946], 11); leaflet.tileLayer('https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png', { maxZoom: 19 }).addTo(m); mapRef.current = m; m.whenReady(() => setIsMapReady(true)); }; const existingL = (window as any).L; if (existingL) { setL(existingL); initMap(existingL); } else { const script = document.createElement('script'); script.src = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.js'; script.async = true; script.onload = () => { const leaflet = (window as any).L; if (leaflet) { setL(leaflet); initMap(leaflet); } }; document.head.appendChild(script); } return () => { if (mapRef.current) { try { mapRef.current.remove(); } catch (e) { console.warn('Error removing map:', e); } mapRef.current = null; setIsMapReady(false); } }; }, []); React.useEffect(() => { if (!L || !mapRef.current || !isMapReady) return; const map = mapRef.current; // Clear old markers that are no longer in the list Object.keys(markersRef.current).forEach(id => { if (!incidents.find(inc => inc.id === id)) { markersRef.current[id].remove(); delete markersRef.current[id]; } }); const coordMap: { [key: string]: number } = {}; incidents.forEach(inc => { let lat = Number(inc.gps_lat); let lon = Number(inc.gps_lon); // Handle overlapping coordinates with deterministic jitter const coordKey = `${lat.toFixed(5)},${lon.toFixed(5)}`; const count = (coordMap[coordKey] || 0) + 1; coordMap[coordKey] = count; if (count > 1) { // Spiral jitter for better visibility of multiple incidents at same spot const radius = 0.0003 * Math.sqrt(count - 1); const angle = (count - 1) * 137.5 * (Math.PI / 180); // Golden angle lat += radius * Math.cos(angle); lon += radius * Math.sin(angle); } let color = '#F59E0B'; // Default Amber for active const status = inc.status?.toUpperCase(); if (status === 'COMPLETED' || status === 'HANDOVER') { color = '#10B981'; // Green for resolved } else if (status === 'CANCELLED') { color = '#4A5568'; // Gray for cancelled } else if (inc.severity?.toUpperCase() === 'CRITICAL') { color = '#EF4444'; // Red for critical } if (!markersRef.current[inc.id]) { const icon = L.divIcon({ className: 'custom-incident-marker', html: `
`, iconSize: [12, 12], iconAnchor: [6, 6] }); const callerName = inc.guest_name || inc.caller_id || 'Unknown'; const callerPhone = inc.guest_phone || 'N/A'; const patientCount = inc.patients?.length || 0; markersRef.current[inc.id] = L.marker([lat, lon], { icon }) .addTo(map) .bindPopup(`
#${inc.id.split('-').pop()?.toUpperCase()} ${inc.status}
${inc.category} • ${inc.severity}
📍 ${inc.address}
Caller ${callerName}
Phone ${callerPhone}
${patientCount} PATIENT${patientCount !== 1 ? 'S' : ''} DETECTED
${inc.patients && inc.patients.length > 0 ? inc.patients.map((p: any) => `
${p.name || 'Anonymous'} (${p.age || '?'}${p.gender ? p.gender[0] : ''}) ${p.symptoms?.map((s: any) => typeof s === 'string' ? s : s.name).join(', ') || 'No symptoms'}
`).join('') : 'No patient data'}
`, { className: 'glass-popup', maxWidth: 300 }); } else { markersRef.current[inc.id].setLatLng([lat, lon]); } }); // Auto-fit map to show all incidents if (incidents.length > 0 && map && isMapReady) { try { const validCoords = incidents .map(i => [Number(i.gps_lat), Number(i.gps_lon)]) .filter(c => Number.isFinite(c[0]) && Number.isFinite(c[1]) && Math.abs(c[0]) <= 90 && Math.abs(c[1]) <= 180 && (c[0] !== 0 || c[1] !== 0) // Ignore 0,0 placeholders ); if (validCoords.length > 0) { const bounds = L.latLngBounds(validCoords as any); const container = map.getContainer(); if (bounds.isValid() && container.offsetWidth > 0 && container.offsetHeight > 0) { // If all points are at the exact same location, fitBounds can sometimes fail or behave weirdly const sw = bounds.getSouthWest(); const ne = bounds.getNorthEast(); if (sw.lat === ne.lat && sw.lng === ne.lng) { map.setView(sw, 14); } else { map.fitBounds(bounds, { padding: [50, 50], maxZoom: 14 }); } } } } catch (err) { // Suppress specific "Bounds are not valid" error as we handle it defensively now if (!(err instanceof Error && err.message.includes('Bounds are not valid'))) { console.error('Map fitBounds error:', err); } } } else if (map && isMapReady) { // Default view if no incidents map.setView([12.9716, 77.5946], 11); } map.on('click', (e: any) => { const { lat, lng } = e.latlng; // Emit a custom event or use a ref to open the modal from the parent const event = new CustomEvent('map-click-add', { detail: { lat, lng } }); window.dispatchEvent(event); }); }, [incidents, L, isMapReady]); return (
{!L &&
INITIALIZING GLOBAL HEATMAP...
}
); }; // --- CUSTOM CHART COMPONENTS --- const CustomChartTooltip = ({ active, payload }: any) => { if (active && payload && payload.length) { return (
{payload[0].name} Status
{payload[0].value} ASSETS
); } return null; }; // --- PREMIUM COMPONENTS --- const PremiumStatCard: React.FC<{ label: string; value: string | number; subValue?: string; icon: any; trend?: { value: string; isUp: boolean }; glowColor: 'cyan' | 'green' | 'red' | 'amber'; pulse?: boolean; }> = ({ label, value, subValue, icon: Icon, trend, glowColor, pulse }) => { const colors = { cyan: { bg: 'rgba(59, 130, 246, 0.1)', text: 'var(--accent-cyan)' }, green: { bg: 'rgba(16, 185, 129, 0.1)', text: 'var(--accent-green)' }, red: { bg: 'rgba(239, 68, 68, 0.1)', text: 'var(--alert-red)' }, amber: { bg: 'rgba(245, 158, 11, 0.1)', text: 'var(--warning-amber)' }, }; const theme = colors[glowColor]; return (
{pulse &&
}
{label}
{value} {subValue && / {subValue}}
{trend && (
{trend.isUp ? '↑' : '↓'} {trend.value} vs last hour
)}
); }; export const Dashboard: React.FC = () => { const [incidents, setIncidents] = useState([]); const [users, setUsers] = useState([]); const [auditLogs, setAuditLogs] = useState([]); const [isLoading, setIsLoading] = useState(true); const [lastUpdated, setLastUpdated] = useState(new Date()); const user = useMemo(() => { try { const stored = localStorage.getItem('teleems_user'); if (!stored || stored === 'undefined' || stored === 'null') return {}; const parsed = JSON.parse(stored); return parsed && typeof parsed === 'object' ? parsed : {}; } catch { return {}; } }, []); const token = localStorage.getItem('teleems_token') || ''; const roles = Array.isArray(user.roles) ? user.roles : []; const isFleetOp = roles.includes('FLEET_OPERATOR'); const isHospitalAdmin = roles.some((r: string) => r.toUpperCase() === 'HOSPITAL_ADMIN' || r.toUpperCase() === 'HOSPITAL ADMIN'); const orgName = user.metadata?.organization?.company_name || (isHospitalAdmin ? 'Hospital' : 'Fleet Operator'); const [isAddModalOpen, setIsAddModalOpen] = useState(false); const [clickCoords, setClickCoords] = useState<{ lat: number, lng: number } | null>(null); const [newIncident, setNewIncident] = useState({ category: 'MEDICAL', severity: 'HIGH', address: '', notes: '' }); useEffect(() => { const handleMapClick = (e: any) => { setClickCoords(e.detail); setNewIncident(prev => ({ ...prev, address: `Lat: ${e.detail.lat.toFixed(4)}, Lon: ${e.detail.lng.toFixed(4)}` })); setIsAddModalOpen(true); }; window.addEventListener('map-click-add', handleMapClick); return () => window.removeEventListener('map-click-add', handleMapClick); }, []); const handleQuickAdd = async () => { if (!token || !clickCoords) return; try { const payload = { ...newIncident, gps_lat: clickCoords.lat, gps_lon: clickCoords.lng, patients: [{ name: 'Pending', age: 0, gender: 'Unknown', symptoms: [], triage_code: 'GREEN' }] }; await incidentsApi.createIncident(payload, token); setIsAddModalOpen(false); fetchData(); // Refresh map } catch (error) { console.error('Failed to quick-add incident:', error); } }; const fetchData = async () => { if (!token) return; setIsLoading(true); try { // Use individual try-catches or settle all to ensure one failure doesn't block the rest const [incRes, userRes, auditRes] = await Promise.allSettled([ incidentsApi.getIncidents({}, token), authApi.getUsers(token), authApi.getAuditLogs(token) ]); if (incRes.status === 'fulfilled' && incRes.value && incRes.value.data) { const processed = (incRes.value.data || []).map((inc: any) => ({ ...inc, gps_lat: Number(inc.gps_lat), gps_lon: Number(inc.gps_lon) })); setIncidents(processed); } else if (incRes.status === 'rejected') { console.error('Failed to fetch incidents:', incRes.reason); } if (userRes.status === 'fulfilled' && userRes.value && userRes.value.data) { setUsers(Array.isArray(userRes.value.data) ? userRes.value.data : []); } if (auditRes.status === 'fulfilled' && auditRes.value && !auditRes.value.status) { setAuditLogs(Array.isArray(auditRes.value.data) ? auditRes.value.data : (Array.isArray(auditRes.value.logs) ? auditRes.value.logs : [])); } else { setAuditLogs([]); if (auditRes.status === 'rejected') { console.warn('Audit logs unavailable'); } } setLastUpdated(new Date()); } catch (error) { console.error('Failed to fetch dashboard data:', error); } finally { setIsLoading(false); } }; useEffect(() => { fetchData(); const interval = setInterval(fetchData, 30000); // Poll every 30s return () => clearInterval(interval); }, [token]); // Derived Metrics const activeIncidents = incidents.filter(i => !['COMPLETED', 'CANCELLED', 'HANDOVER'].includes(i.status?.toUpperCase()) ); const fleetOperators = users.filter((u: any) => { const r = Array.isArray(u.roles) ? u.roles.map((sr: any) => String(sr).toUpperCase()) : []; return r.includes('FLEET_OPERATOR') || r.includes('FLEET OPERATOR'); }); const criticalIssues = incidents.filter(i => i.severity?.toUpperCase() === 'CRITICAL'); const fleetStatusData = [ { name: 'IDLE', value: users.filter(u => u.status === 'ACTIVE').length, color: '#3B82F6' }, { name: 'ACTIVE', value: activeIncidents.length, color: '#10B981' }, { name: 'ALERT', value: criticalIssues.length, color: '#EF4444' }, { name: 'OFFLINE', value: users.filter(u => u.status === 'INACTIVE').length || 2, color: '#4A5568' }, ]; const activityData = Array.isArray(auditLogs) ? auditLogs.slice(0, 7).reverse().map((log) => ({ time: log.timestamp ? new Date(log.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : '--:--', count: Math.floor(Math.random() * 20) + 10 // Mocking activity intensity from audit density })) : []; return (
{/* Header Section */}

{isFleetOp ? `${orgName} Command` : isHospitalAdmin ? `${orgName} Administration` : 'Super Admin Command Center'}

Live platform telemetry synchronized at {lastUpdated.toLocaleTimeString()}

{fleetOperators.length} OPERATORS ACTIVE
{/* Primary Stats Bar */}
0} trend={{ value: '14%', isUp: true }} /> u.roles?.includes('CCE')).length || 4} icon={Video} glowColor="cyan" />
{/* Main Operational Grid: 2 Columns */}
{/* Real-time Heatmap */}

Global Incident Explorer

System-wide incident history and live telemetry

CRITICAL
ACTIVE (L/M)
RESOLVED
{/* Global Distribution & Health */}
{fleetStatusData.map((entry, index) => ( ))} } cursor={{ fill: 'transparent' }} /> {/* Central Stat */}
Total
{fleetStatusData.reduce((acc, curr) => acc + curr.value, 0)}
ASSETS
{fleetStatusData.map(item => { const total = fleetStatusData.reduce((acc, curr) => acc + curr.value, 0); const percentage = total > 0 ? Math.round((item.value / total) * 100) : 0; return (
{item.name}
{percentage}%
); })}
{/* Secondary Grid: Governance Feed and Performance */}
{/* Governance Feed */}
{incidents.slice(0, 8).map((inc) => (
#{inc.id.split('-').pop()} {inc.address}
{inc.status}
{inc.eta_seconds ? `${Math.floor(inc.eta_seconds / 60)}m` : '--'}
ETA
))} {incidents.length === 0 &&
No active incidents
}
{/* Platform DNA Section */}
SYNCED
Master Data

482 Triage rules active.

100%
Compliance

HIPAA / ABDM verified.

STABLE
System Logic

SLA thresholds active.

ACTIVE
Network Hub

Multi-zone sync active.

{[ { label: 'Blood Link', status: 'Healthy', color: 'var(--accent-green)' }, { label: 'Organ Registry', status: 'Healthy', color: 'var(--accent-green)' }, { label: 'Mortuary Sync', status: 'Delayed', color: 'var(--warning-amber)' }, { label: 'Police V-Link', status: 'Healthy', color: 'var(--accent-green)' }, ].map((r, i) => (
{r.label}
{r.status}
))}
{/* SLA Ticker & Progress */}
{[ { label: 'Foundation', progress: 100 }, { label: 'MVP Core', progress: 100 }, { label: 'Clinical AI', progress: 85 }, { label: 'Fleet Intel', progress: 42 }, { label: 'Compliance', progress: 100 }, ].map((phase, i) => (
{phase.label} {phase.progress}%
))}
SLA TICKER
HIPAA COMPLIANT    |    ABDM SYNCED    |    ISO 27001 AUDIT PASSED    |    PHI ENCRYPTED    |    DPDP ACT ALIGNED    |    END-TO-END TLS 1.3 ACTIVE
{/* Quick Add Modal */} {isAddModalOpen && (

QUICK LOG INCIDENT

{clickCoords?.lat.toFixed(6)}, {clickCoords?.lng.toFixed(6)}
{['LOW', 'HIGH', 'CRITICAL'].map(s => ( ))}