"use client"; import { useState, useEffect, type ReactNode } from "react"; import Link from "next/link"; import UpgradePlanModal from "@/components/admin/UpgradePlanModal"; import { PageHeader, AdminButton, AdminFilterTabs, AdminBadge } from "@/components/admin/design-system"; import { getDashboardStats, type DashboardStats } from "@/actions/dashboard"; type Section = { title: string; href: string; description: string; group: "operations" | "fulfillment" | "management" | "tools"; addonKey?: string; upgradeText?: string; prominent?: boolean; }; const sections: Section[] = [ { title: "Orders", href: "/admin/orders", description: "View orders, pickup status, fulfillment, and customer details.", group: "operations", prominent: true, }, { title: "Products", href: "/admin/products", description: "Manage products, pricing, shipping type, and availability.", group: "operations", prominent: true, }, { title: "Tours & Stops", href: "/admin/stops", description: "Manage routes, pickup locations, dates, and cutoff times.", group: "fulfillment", }, { title: "Driver Pickup", href: "/admin/pickup", description: "Mobile pickup lookup, QR scanning, and completion tools.", group: "fulfillment", }, { title: "Shipping", href: "/admin/shipping", description: "FedEx integration, label creation, and shipment tracking.", group: "fulfillment", }, { title: "Reports", href: "/admin/reports", description: "Sales, route, product, pickup, and customer reports.", group: "management", }, { title: "Tax Dashboard", href: "/admin/taxes", description: "Sales tax collected, breakdown by state, and exportable reports.", group: "management", }, { title: "Settings", href: "/admin/settings", description: "Users, billing, brand, integrations, payments, and shipping.", group: "management", }, { title: "Harvest Reach", href: "/admin/communications", description: "Email campaigns, stop blast, templates, and audience segments.", group: "tools", addonKey: "harvest_reach", upgradeText: "Enable to access email & SMS marketing", }, { title: "Wholesale Portal", href: "/admin/wholesale", description: "Standalone B2B portal with custom pricing, credit limits, and net-30.", group: "tools", addonKey: "wholesale_portal", upgradeText: "Enable to unlock B2B buyer portal", }, { title: "Import Center", href: "/admin/import", description: "AI-powered import for products, orders, contacts, and stops.", group: "tools", addonKey: "ai_tools", upgradeText: "Enable AI import with smart column mapping", }, { title: "AI Intelligence", href: "/admin/settings/ai", description: "Campaign writer, pricing advisor, and report explainer.", group: "tools", addonKey: "ai_tools", upgradeText: "Enable AI tools for marketing and pricing", }, { title: "Time Tracking", href: "/admin/time-tracking", description: "Worker clock-in/out, hours tracking, and overtime management.", group: "tools", addonKey: "time_tracking", upgradeText: "Enable for field worker time tracking", }, { title: "Water Log", href: "/admin/water-log", description: "Irrigation tracking and water usage reporting.", group: "tools", addonKey: "water_log", upgradeText: "Enable for agricultural water tracking", }, { title: "Route Trace", href: "/admin/route-trace", description: "Lot tracking, QR stickers, hauling board, and supply chain traceability.", group: "tools", addonKey: "route_trace", upgradeText: "Enable for field-to-delivery traceability", }, ]; type Tab = "operations" | "fulfillment" | "management" | "tools"; const TABS: { id: Tab; label: string; icon: ReactNode }[] = [ { id: "operations", label: "Operations", icon: ( ), }, { id: "fulfillment", label: "Fulfillment", icon: ( ), }, { id: "management", label: "Management", icon: ( ), }, { id: "tools", label: "Tools", icon: ( ), }, ]; type Props = { brandId: string | null; brandName: string; planTier: string; isWaterLogVisible: boolean; enabledAddons: Record; usage: { users: number; stops_this_month: number; products: number }; limits: { max_users: number; max_stops_monthly: number; max_products: number }; }; export default function DashboardClient({ brandId, brandName, planTier, isWaterLogVisible, enabledAddons, usage, limits, }: Props) { const [activeTab, setActiveTab] = useState("operations"); const [isUpgradeOpen, setIsUpgradeOpen] = useState(false); const [stats, setStats] = useState(null); const [isLoadingStats, setIsLoadingStats] = useState(true); useEffect(() => { const loadStats = async () => { setIsLoadingStats(true); try { const data = await getDashboardStats(); setStats(data); } catch (err) { console.error("Failed to load stats:", err); } finally { setIsLoadingStats(false); } }; loadStats(); }, []); const usagePct = { users: limits.max_users > 0 ? (usage.users / limits.max_users) * 100 : 0, stops: limits.max_stops_monthly > 0 ? (usage.stops_this_month / limits.max_stops_monthly) * 100 : 0, products: limits.max_products > 0 ? (usage.products / limits.max_products) * 100 : 0, }; const tabSections = sections.filter((s) => s.group === activeTab); // Format currency const formatCurrency = (amount: number) => { return new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", }).format(amount); }; // Get status badge color const getStatusBadge = (status: string) => { const styles: Record = { pending: { bg: "var(--admin-warning-light)", text: "var(--admin-warning)" }, processing: { bg: "var(--admin-accent-light)", text: "var(--admin-accent-text)" }, shipped: { bg: "#dbeafe", text: "#1e40af" }, }; return styles[status] || { bg: "var(--admin-bg)", text: "var(--admin-text-secondary)" }; }; // Quick action buttons const quickActions = [ { label: "New Order", href: "/admin/orders?new=true", icon: "plus" }, { label: "Add Stop", href: "/admin/stops/new", icon: "map" }, { label: "Add Product", href: "/admin/products/new", icon: "package" }, { label: "Send Blast", href: "/admin/communications/compose", icon: "mail" }, ]; return (
{/* Page Header */}
} title="Admin Dashboard" subtitle={`${brandName} Control Center`} actions={
Billing → {planTier === "starter" && brandId && ( setIsUpgradeOpen(true)} size="md" > Upgrade Plan )}
} className="mb-0" />
{/* Content */}
{/* Stats Cards Row */}
{/* Today's Orders */}

Today's Orders

{isLoadingStats ? "—" : stats?.todayOrders ?? 0}

{/* Today's Revenue */}

Today's Revenue

{isLoadingStats ? "—" : formatCurrency(stats?.todayRevenue ?? 0)}

{/* Pending Stops */}

Pending Stops

{isLoadingStats ? "—" : stats?.pendingStops ?? 0}

{/* Active Products — uses plan-aware usage.products so this card always matches the "Products 0/25" usage bar below and the billing page's invoice/usage row. Previously this came from a separate query (`active=eq.true` only) and could disagree with the plan limit usage, producing e.g. "1 vs 0/25" in the same dashboard. */}

Active Products

{/* usage.products comes from the server-rendered prop (via getBillingOverview), so it's available immediately and is guaranteed to match the "Products X/25" usage bar and the billing page. */} {usage.products}

{/* Quick Actions + Recent Orders Row */}
{/* Quick Actions */}

Quick Actions

{quickActions.map((action) => (
{action.icon === "plus" && ( )} {action.icon === "map" && ( )} {action.icon === "package" && ( )} {action.icon === "mail" && ( )}
{action.label} ))}
{/* Recent Orders */}

Recent Orders

View all →
{stats?.recentOrders && stats.recentOrders.length > 0 ? ( stats.recentOrders.map((order) => { const badge = getStatusBadge(order.status); return (

{order.customer_name}

{order.created_at}

{formatCurrency(order.total)} {order.status}
); }) ) : (

No recent orders

Create your first order →
)}
{/* Usage stats bar */}
{planTier.charAt(0).toUpperCase() + planTier.slice(1)} Plan {brandId ? brandName : "All Brands"}
{[ { label: "Users", value: `${usage.users}/${limits.max_users}`, pct: usagePct.users, icon: "users" }, { label: "Stops", value: `${usage.stops_this_month}/${limits.max_stops_monthly}`, pct: usagePct.stops, icon: "map" }, { label: "Products", value: `${usage.products}/${limits.max_products}`, pct: usagePct.products, icon: "package" }, ].map(({ label, value, pct }) => (
{label === "Users" && ( )} {label === "Stops" && ( )} {label === "Products" && ( )} {label}
{value}
90 ? "var(--admin-danger)" : pct > 75 ? "#f59e0b" : "var(--admin-accent)" }} />
{pct > 85 && (

Near limit - consider upgrading

)}
))}
{/* Tab navigation */} setActiveTab(value as Tab)} tabs={TABS.map((tab) => ({ value: tab.id, label: tab.label, icon: tab.icon, }))} size="md" showCounts={false} /> {/* Section Cards Grid */}
{tabSections.map((section) => { if (section.title === "Water Log" && !isWaterLogVisible) return null; if (section.title === "Route Trace" && !enabledAddons["route_trace"]) return null; const isAddon = Boolean(section.addonKey); const isEnabled = section.addonKey ? (enabledAddons[section.addonKey] ?? false) : true; const isProminent = section.prominent; return (
{section.title === "Orders" && ( )} {section.title === "Products" && ( )} {section.title === "Tours & Stops" && ( )} {section.title === "Driver Pickup" && ( )} {!["Orders", "Products", "Tours & Stops", "Driver Pickup"].includes(section.title) && ( )}
{isAddon && !isEnabled && ( Add-on )} {isAddon && isEnabled && ( Active )} {isProminent && ( Core )}

{section.title}

{section.description}

{isAddon && !isEnabled && section.upgradeText && (

{section.upgradeText}

)} {/* Arrow indicator */}
Open section
); })}
{/* Upgrade Modal */} {planTier === "starter" && brandId && ( setIsUpgradeOpen(false)} brandId={brandId} currentTier={planTier} /> )}
); }