import { useQuery } from "@tanstack/react-query" import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card" import { Button } from "@/components/ui/button" import { Download, Users, FileText, DollarSign, HardDrive, AlertCircle } from "lucide-react" import { analyticsService, systemService } from "@/services" import { LineChart, Line, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from "recharts" import { toast } from "sonner" export default function DashboardPage() { const { data: overview, isLoading: overviewLoading } = useQuery({ queryKey: ['admin', 'analytics', 'overview'], queryFn: () => analyticsService.getOverview(), }) const { data: userGrowth, isLoading: growthLoading } = useQuery({ queryKey: ['admin', 'analytics', 'users', 'growth'], queryFn: () => analyticsService.getUserGrowth(30), }) const { data: revenue, isLoading: revenueLoading } = useQuery({ queryKey: ['admin', 'analytics', 'revenue'], queryFn: () => analyticsService.getRevenue('30days'), }) const { data: health, isLoading: healthLoading } = useQuery({ queryKey: ['admin', 'system', 'health'], queryFn: () => systemService.getHealth(), }) const { data: errorRate, isLoading: errorRateLoading } = useQuery({ queryKey: ['admin', 'analytics', 'error-rate'], queryFn: () => analyticsService.getErrorRate(7), }) const handleExport = () => { try { // Create CSV content from current dashboard data const csvContent = [ ['Metric', 'Value'], ['Total Users', overview?.users?.total || 0], ['Active Users', overview?.users?.active || 0], ['Inactive Users', overview?.users?.inactive || 0], ['Total Invoices', overview?.invoices?.total || 0], ['Total Revenue', overview?.revenue?.total || 0], ['Storage Used', overview?.storage?.totalSize || 0], ['Total Documents', overview?.storage?.documents || 0], ['Error Rate', errorRate?.errorRate || 0], ['Total Errors', errorRate?.errors || 0], ['Export Date', new Date().toISOString()], ] .map(row => row.join(',')) .join('\n') // Create and download the file const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' }) const url = window.URL.createObjectURL(blob) const link = document.createElement('a') link.href = url link.download = `admin-dashboard-${new Date().toISOString().split('T')[0]}.csv` document.body.appendChild(link) link.click() document.body.removeChild(link) window.URL.revokeObjectURL(url) toast.success("Dashboard data exported successfully!") } catch (error) { toast.error("Failed to export data. Please try again.") console.error('Export error:', error) } } const formatCurrency = (amount: number) => { return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', }).format(amount) } const formatBytes = (bytes: number) => { if (bytes === 0) return '0 Bytes' const k = 1024 const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'] const i = Math.floor(Math.log(bytes) / Math.log(k)) return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i] } return (

Dashboard Overview

{new Date().toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}
{/* Stats Cards */}
Total Users {overviewLoading ? (
...
) : ( <>
{overview?.users?.total || 0}

{overview?.users?.active || 0} active, {overview?.users?.inactive || 0} inactive

)}
Total Invoices {overviewLoading ? (
...
) : ( <>
{overview?.invoices?.total || 0}

All time invoices

)}
Total Revenue {overviewLoading ? (
...
) : ( <>
{overview?.revenue ? formatCurrency(overview.revenue.total) : '$0.00'}

Total revenue

)}
Storage Usage {overviewLoading ? (
...
) : ( <>
{overview?.storage ? formatBytes(overview.storage.totalSize) : '0 Bytes'}

{overview?.storage?.documents || 0} documents

)}
{/* Charts Row */}
{/* User Growth Chart */} User Growth (Last 30 Days) {growthLoading ? (
Loading...
) : userGrowth && userGrowth.length > 0 ? ( ) : (
No data available
)}
{/* Revenue Chart */} Revenue Analytics (Last 30 Days) {revenueLoading ? (
Loading...
) : revenue && revenue.length > 0 ? ( ) : (
No data available
)}
{/* Error Rate Chart */} {errorRate && ( Error Rate (Last 7 Days) {errorRateLoading ? (
Loading...
) : (

Total Errors

{errorRate.errors || 0}

Total Requests

{errorRate.total || 0}

Error Rate

{errorRate.errorRate ? `${errorRate.errorRate.toFixed(2)}%` : '0%'}

)} )} {/* System Health */} System Health {healthLoading ? (
Loading system health...
) : (

Status

{health?.status || 'Unknown'}

Database

{health?.database || 'Unknown'}

Recent Errors

{health?.recentErrors || 0}

Active Users

{health?.activeUsers || 0}

)}
) }