'use client'; import { ArrowRight, TrendingUp, Filter, Users, Activity, PackageCheck, ShoppingBag, } from 'lucide-react'; import { ComposedChart, Bar, Area, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid, } from 'recharts'; import { DashboardRevenuePoint, DashboardMonthlyPoint, } from '@/services/api/adminService'; import { cn } from '@/lib/utils'; import Link from 'next/link'; import { DashboardHeaderNav } from '@/components/dashboard/DashboardHeaderNav'; import { TopSellingProductsCard } from '@/components/dashboard/TopSellingProductsCard'; import { useDashboardData } from '@/components/dashboard/useDashboardData'; import { isRouteAllowed } from '@/lib/rbac'; import { CARD, PIPELINE, OVERVIEW, DONUT_COLORS, PAYMENT_TAG, PRODUCT_TONES, formatCompact, formatInr, initials, samplePoints, deltaFromWeek, CardTitle, PeriodPills, GhostSelect, DeltaPill, StatusDonut, } from '@/components/dashboard/DashboardShared'; export default function MainDashboardPage() { const { stats: displayStats, sessions, loading, refreshing, userName, userRole, chartMode, setChartMode, fetchData, } = useDashboardData(); const byStatus = displayStats.orders_by_status ?? {}; const countOf = (key: string) => byStatus[key] ?? 0; const totalOrders = displayStats.total_orders ?? 0; const delivered = countOf('delivered'); const conversion = totalOrders > 0 ? (delivered / totalOrders) * 100 : 0; const revenueDelta = deltaFromWeek( displayStats.revenue_last_7_days ?? 0, displayStats.revenue_last_30_days ?? 0 ); const ordersDelta = conversion >= 40 ? 2.5 : -4.2; const conversionDelta = 15.5; const customersDelta = 2.5; const daily: DashboardRevenuePoint[] = displayStats.revenue_chart_daily ?? []; const monthly: DashboardMonthlyPoint[] = displayStats.revenue_chart_monthly ?? []; const sourceChart: Array = chartMode === 'weekly' ? samplePoints(daily, 12) : monthly; const rawPoints = sourceChart.map((row) => ({ name: 'date' in row ? row.date?.replace('08-', '') ?? '' : row.label?.slice(0, 3) ?? '', revenue: row.revenue, orders: row.orders, })); const maxRev = Math.max(...rawPoints.map((row) => row.revenue), 1); const maxOrd = Math.max(...rawPoints.map((row) => row.orders), 1); const salesScale = (maxRev * 0.72) / maxOrd; const chartPoints = rawPoints.map((row) => ({ ...row, sales: row.orders * salesScale, })); const pipelineRows = PIPELINE.map((stage) => ({ ...stage, count: countOf(stage.key), value: countOf(stage.key) * (displayStats.revenue_all_time / Math.max(totalOrders, 1)), })); const maxPipeline = Math.max(...pipelineRows.map((row) => row.count), 1); const overviewRows = OVERVIEW.map((row) => ({ ...row, count: countOf(row.key), })); const overviewTotal = overviewRows.reduce((sum, row) => sum + row.count, 0) || 1; const donutSlices = [ { label: 'Delivered', value: countOf('delivered'), color: DONUT_COLORS.delivered }, { label: 'Shipped', value: countOf('shipped'), color: DONUT_COLORS.shipped }, { label: 'Processing', value: countOf('processing') + countOf('confirmed'), color: DONUT_COLORS.processing }, { label: 'Pending', value: countOf('pending') + countOf('cancelled') + countOf('returned'), color: DONUT_COLORS.pending }, ].filter((slice) => slice.value > 0); const spark = daily.slice(-14).map((row) => row.orders); const sparkMax = Math.max(...spark, 1); const customerAvatars = (displayStats.recent_orders ?? []).slice(0, 4); if (loading) { return (
{[...Array(4)].map((_, i) => (
))}
); } return (
fetchData(true)} /> {/* Top Analytics Row */}
{/* Revenue Analytics Chart */}
Revenue Analytics

{formatCompact(displayStats.revenue_last_30_days).replace('₹', '')}

Revenue with orders (INR)

Revenue Orders
(v >= 1000 ? `₹${(v / 1000).toFixed(0)}k` : `₹${v}`)} /> { if (!active || !payload?.length) return null; const row = payload[0]?.payload as { revenue: number; orders: number }; return (

{label}

{formatInr(row.revenue)}

{row.orders} orders

); }} />
{/* Order Status Pipeline */}
Order Status Pipeline
{pipelineRows.map((row) => (

{row.label}

{row.count}

{formatCompact(row.value)}

))}
{pipelineRows.map((row) => (
{row.label}
))}
{/* KPI Stats Grid */}
{/* Total Revenue */}

Total Revenue

{formatInr(displayStats.revenue_all_time)}

vs previous 30 days
{/* Total Orders */}

Total Orders

{totalOrders.toLocaleString()}

Order volume
{spark.length > 0 && (
{spark.map((v, i) => ( ))}
)}
{/* Delivery Success Rate */}

Delivery Success Rate

{conversion.toFixed(1)}%

Fulfilled vs Total
{/* Total Customers */}

Total Customers

{displayStats.total_users.toLocaleString()}

Platform accounts
{customerAvatars.length > 0 && (
{customerAvatars.map((c, i) => ( {initials(c.customer_name)} ))}
)}
{/* Middle Grid: Order Status Breakdown & Live Sessions */}
{/* Order Status Breakdown */}
Order Status Breakdown
{overviewRows.map((row) => { const pct = Math.round((row.count / overviewTotal) * 100); return (
{row.label}
{row.count} {pct}%
); })}
{/* Live Admin Sessions */}
Live System Sessions {sessions.length} Active
{isRouteAllowed('/security', userRole) && ( Manage Security )}
{sessions.length === 0 ? ( ) : ( sessions.slice(0, 5).map((s) => ( )) )}
User Identifier IP Address Client Device State
No active sessions recorded
{s.user_id} {s.ip_address || '—'} {s.browser || s.device_name || 'Web Client'} Online
{/* Recent Orders & Top Selling Products */}
{/* Recent Orders Table */}
Recent Orders
Filter See all
{(displayStats.recent_orders ?? []).length === 0 ? ( ) : ( (displayStats.recent_orders ?? []).map((order) => ( )) )}
Order Date Total Status Payment
No recent orders found
{order.order_no} {order.created_at ? new Date(order.created_at).toLocaleDateString('en-IN', { day: '2-digit', month: 'short' }) : '—'} {formatInr(order.amount)} {order.status} {order.payment_status || '—'}
{/* Top Selling Products with 3D Isometric PillarGrid */}
); }