"use client" import { useState, useEffect } from "react" import OrderStats from "./order-stats" import { getGreeting } from "@/lib/utils" import { statsConfig } from "@/config/dashboard" import type { OrderStatsData } from "@/lib/types" import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" import { ShoppingCart, RefreshCcw } from "lucide-react" import { Button } from "@/components/ui/button" import { useToast } from "@/components/ui/use-toast" import { Skeleton } from "@/components/ui/skeleton" interface ContentProps { username: string orderStats: OrderStatsData } interface TopProduct { id: string; name: string; price: number; image: string; count: number; revenue: number; } // Business quotes array const businessQuotes = [ { text: "Your most unhappy customers are your greatest source of learning.", author: "Bill Gates" }, { text: "The secret of getting ahead is getting started.", author: "Mark Twain" }, { text: "Success is not final; failure is not fatal: It is the courage to continue that counts.", author: "Winston Churchill" }, { text: "The way to get started is to quit talking and begin doing.", author: "Walt Disney" }, { text: "Opportunities don't happen. You create them.", author: "Chris Grosser" }, { text: "The best way to predict the future is to create it.", author: "Peter Drucker" }, { text: "Don't watch the clock; do what it does. Keep going.", author: "Sam Levenson" }, { text: "The future belongs to those who believe in the beauty of their dreams.", author: "Eleanor Roosevelt" }, { text: "Entrepreneurship is living a few years of your life like most people won't so you can spend the rest of your life like most people can't.", author: "Anonymous" }, { text: "Your work is going to fill a large part of your life, and the only way to be truly satisfied is to do what you believe is great work.", author: "Steve Jobs" } ]; // Function to get a random quote that's not the Mark Twain one function getRandomQuote() { // Filter out the Mark Twain quote for now to ensure variety const filteredQuotes = businessQuotes.filter(quote => quote.author !== "Mark Twain"); const randomIndex = Math.floor(Math.random() * filteredQuotes.length); return filteredQuotes[randomIndex]; } export default function Content({ username, orderStats }: ContentProps) { const [greeting, setGreeting] = useState("") const [topProducts, setTopProducts] = useState([]) const [isLoading, setIsLoading] = useState(true) const [error, setError] = useState(null) const { toast } = useToast() // Initialize with a random quote that's not Mark Twain const [randomQuote, setRandomQuote] = useState(getRandomQuote()) const fetchTopProducts = async () => { setIsLoading(true) setError(null) try { // Get the auth token from cookies const authToken = document.cookie .split("; ") .find((row) => row.startsWith("Authorization=")) ?.split("=")[1]; if (!authToken) { throw new Error("Authentication token not found") } // Use the API URL from environment variables const apiUrl = `${process.env.NEXT_PUBLIC_API_URL}/orders/top-products`; const response = await fetch(apiUrl, { headers: { Authorization: `Bearer ${authToken}`, 'Content-Type': 'application/json' } }); if (!response.ok) { throw new Error(`API request failed: ${response.status} ${response.statusText}`) } const data = await response.json(); setTopProducts(data); } catch (err) { console.error("Error fetching top products:", err); setError(err instanceof Error ? err.message : "Failed to fetch top products") toast({ title: "Error loading top products", description: "Please try refreshing the page", variant: "destructive" }) } finally { setIsLoading(false) } }; useEffect(() => { setGreeting(getGreeting()) // Fetch top products fetchTopProducts(); }, []) return (

{greeting}, {username}!

"{randomQuote.text}" — {randomQuote.author}

{statsConfig.map((stat) => ( ))}
{/* Best Selling Products Section */}
Your Best Selling Products Products with the highest sales from your store
{error && ( )}
{isLoading ? (
{[...Array(5)].map((_, i) => (
))}
) : error ? (

Error loading products

{error}

) : topProducts.length > 0 ? (
{topProducts.map(product => (
{product.image ? ( {product.name} { const target = e.currentTarget; target.src = ""; if (target.parentElement) { target.parentElement.classList.add("bg-muted"); const iconSpan = document.createElement("span"); iconSpan.className = "h-5 w-5 text-muted-foreground"; target.parentElement.appendChild(iconSpan); } }} /> ) : ( )}

{product.name}

{product.count} sold

))}
) : (

No sales data available yet

Your best-selling products will appear here once you have orders

)}
) }