import { useMemo } from 'react'; import { useNavigate } from 'react-router-dom'; import { BarChart3, Briefcase, DollarSign, MapPin, Plus, Search, Target, TrendingUp, Users, Leaf } from 'lucide-react'; import { MainLayout } from '@/components/layout/MainLayout.tsx'; import PageHeader from '@/components/layout/PageHeader.tsx'; import Badge from '@/components/ui/Badge.tsx'; import Button from '@/components/ui/Button.tsx'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/Card.tsx'; import MetricItem from '@/components/ui/MetricItem.tsx'; import Spinner from '@/components/ui/Spinner.tsx'; import { Container, Flex, Grid, Stack } from '@/components/ui/layout'; import { useAuth } from '@/contexts/AuthContext.tsx'; import { useDashboardStatistics, useImpactMetrics, useMatchingStatistics, usePlatformStatistics } from '@/hooks/api/useAnalyticsAPI.ts'; import { useProposals } from '@/hooks/api/useProposalsAPI.ts'; import { useTranslation } from '@/hooks/useI18n.tsx'; import { useNavigation } from '@/hooks/useNavigation.tsx'; import { useOrganizations } from '@/hooks/useOrganizations.ts'; const DashboardPage = () => { const { t } = useTranslation(); const navigate = useNavigate(); const { handleBackNavigation, handleFooterNavigate } = useNavigation(); const { user } = useAuth(); // Analytics data const { data: dashboardStats, isLoading: isLoadingDashboard } = useDashboardStatistics(); const { data: platformStats, isLoading: isLoadingPlatform } = usePlatformStatistics(); const { data: matchingStats, isLoading: isLoadingMatching } = useMatchingStatistics(); const { data: impactMetrics, isLoading: isLoadingImpact } = useImpactMetrics(); // User-specific data const { data: proposalsData } = useProposals(); const { organizations } = useOrganizations(); // Calculate derived statistics const stats = useMemo(() => { const dashboard = dashboardStats || {}; const platform = platformStats || {}; const matching = matchingStats || {}; const impact = impactMetrics || {}; // Safely handle proposals data const proposals: any[] = Array.isArray(proposalsData?.proposals) ? proposalsData.proposals : []; const pendingProposals = proposals.filter((p: any) => p?.status === 'pending'); return { totalOrganizations: dashboard.total_organizations || platform.total_organizations || 0, totalSites: dashboard.total_sites || platform.total_sites || 0, totalResourceFlows: dashboard.total_resource_flows || platform.total_resource_flows || 0, totalMatches: dashboard.total_matches || platform.total_matches || 0, activeProposals: dashboard.active_proposals || pendingProposals.length || 0, recentActivity: dashboard.recent_activity || [], // Matching statistics matchSuccessRate: matching.match_success_rate || 0, avgMatchTime: matching.avg_match_time_days || 0, topResourceTypes: matching.top_resource_types || [], // Impact metrics totalCo2Saved: impact.total_co2_saved_tonnes || 0, totalEconomicValue: impact.total_economic_value || 0, activeMatches: impact.active_matches_count || 0, }; }, [dashboardStats, platformStats, matchingStats, impactMetrics, proposalsData]); const formatCurrency = (value: number) => { return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'EUR', minimumFractionDigits: 0, maximumFractionDigits: 0, }).format(value); }; const formatNumber = (value: number) => { return new Intl.NumberFormat('en-US').format(value); }; const isLoading = isLoadingDashboard || isLoadingPlatform || isLoadingMatching || isLoadingImpact; return ( {/* Key Metrics */} } label={t('dashboard.organizations', 'Organizations')} value={formatNumber(stats.totalOrganizations)} /> } label={t('dashboard.sites', 'Sites')} value={formatNumber(stats.totalSites)} /> } label={t('dashboard.resourceFlows', 'Resource Flows')} value={formatNumber(stats.totalResourceFlows)} /> } label={t('dashboard.matches', 'Matches')} value={formatNumber(stats.totalMatches)} /> {/* Impact Metrics */} {(stats.totalCo2Saved > 0 || stats.totalEconomicValue > 0) && (
{t('dashboard.co2Saved', 'CO₂ Saved')}
{formatNumber(stats.totalCo2Saved)} t

{t('dashboard.perYear', 'per year')}

{t('dashboard.economicValue', 'Economic Value')}
{formatCurrency(stats.totalEconomicValue)}

{t('dashboard.created', 'created annually')}

{t('dashboard.activeMatches', 'Active Matches')}
{formatNumber(stats.activeMatches)}

{t('dashboard.operational', 'currently operational')}

)} {/* Quick Actions */} {t('dashboard.quickActions', 'Quick Actions')} {/* Recent Activity & Proposals */} {/* Recent Activity */} {t('dashboard.recentActivity', 'Recent Activity')} {stats.recentActivity.length} {isLoading ? (
) : stats.recentActivity.length > 0 ? (
{stats.recentActivity.slice(0, 5).map((activity: any, index: number) => (

{activity.description}

{new Date(activity.timestamp).toLocaleDateString()}

{activity.type}
))} {stats.recentActivity.length > 5 && (
)}
) : (

{t('dashboard.noRecentActivity', 'No recent activity')}

)} {/* Active Proposals */} {t('dashboard.activeProposals', 'Active Proposals')} {stats.activeProposals} {stats.activeProposals > 0 ? (
{/* This would show actual proposals - placeholder for now */}

{t('dashboard.pendingReviews', 'Pending proposal reviews')}

{stats.activeProposals} {t('dashboard.requireAttention', 'require your attention')}

) : (

{t('dashboard.noActiveProposals', 'No active proposals')}

)}
{/* My Organizations Summary */} {organizations && organizations.length > 0 && ( {t('dashboard.myOrganizations', 'My Organizations')} {organizations.slice(0, 3).map((org: any) => (
navigate(`/organization/${org.ID}`)} >

{org.Name}

{org.sector}

{org.subtype}
))}
)} {/* Platform Health Indicators */} {stats.matchSuccessRate > 0 && ( {t('dashboard.platformHealth', 'Platform Health')}
{Math.round(stats.matchSuccessRate * 100)}%

{t('dashboard.matchSuccessRate', 'Match Success Rate')}

{stats.avgMatchTime.toFixed(1)}

{t('dashboard.avgMatchTime', 'Avg Match Time (days)')}

{stats.topResourceTypes.length}

{t('dashboard.activeResourceTypes', 'Active Resource Types')}

)} ); }; export default DashboardPage;