"use client" import { useState, useEffect } from "react" import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/common/card" import { Button } from "@/components/common/button" import { Skeleton } from "@/components/common/skeleton" import { TrendingUp, DollarSign, RefreshCcw } from "lucide-react" import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from "recharts" import { getRevenueTrendsWithStore, type RevenueData, formatGBP } from "@/lib/api" import { useToast } from "@/components/common/use-toast" interface RevenueWidgetProps { settings?: { days?: number showComparison?: boolean } } interface ChartDataPoint { date: string revenue: number orders: number formattedDate: string } export default function RevenueWidget({ settings }: RevenueWidgetProps) { const days = settings?.days || 7 const [data, setData] = useState([]) const [isLoading, setIsLoading] = useState(true) const [error, setError] = useState(null) const { toast } = useToast() const fetchRevenueData = async () => { try { setIsLoading(true) setError(null) const response = await getRevenueTrendsWithStore(days.toString()) setData(Array.isArray(response) ? response : []) } catch (err) { console.error("Error fetching revenue data:", err) setError("Failed to load revenue data") } finally { setIsLoading(false) } } useEffect(() => { fetchRevenueData() }, [days]) const chartData: ChartDataPoint[] = data.map(item => { const date = new Date(Date.UTC(item._id.year, item._id.month - 1, item._id.day)) return { date: date.toISOString().split('T')[0], revenue: item.revenue || 0, orders: item.orders || 0, formattedDate: date.toLocaleDateString('en-GB', { month: 'short', day: 'numeric', timeZone: 'UTC' }) } }) // Summary stats const totalOrders = data.reduce((sum, item) => sum + (item.orders || 0), 0) const CustomTooltip = ({ active, payload }: any) => { if (active && payload && payload.length) { const data = payload[0].payload return (

{data.formattedDate}

Orders: {data.orders}

) } return null } if (isLoading) { return ( ) } return (
Order Insights Performance over the last {days} days
{error && ( )}
{error ? (

Could not load order trends

) : chartData.length === 0 ? (

No order data

Start making sales to see your order trends here.

) : (
`${value}`} /> } />
Total Orders
{totalOrders}
)}
) }