"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"
import { clientFetch } from "@/lib/client-utils"

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" },
  
  // Additional quotes
  { text: "If you are not willing to risk the usual, you will have to settle for the ordinary.", author: "Jim Rohn" },
  { text: "The only limit to our realization of tomorrow will be our doubts of today.", author: "Franklin D. Roosevelt" },
  { text: "What would you do if you weren't afraid?", author: "Sheryl Sandberg" },
  { text: "The most valuable businesses of coming decades will be built by entrepreneurs who seek to empower people rather than try to make them obsolete.", author: "Peter Thiel" },
  { text: "If you really look closely, most overnight successes took a long time.", author: "Steve Jobs" },
  { text: "Twenty years from now, you will be more disappointed by the things that you didn't do than by the ones you did do.", author: "Mark Twain" },
  { text: "The biggest risk is not taking any risk. In a world that's changing quickly, the only strategy that is guaranteed to fail is not taking risks.", author: "Mark Zuckerberg" },
  { text: "I have not failed. I've just found 10,000 ways that won't work.", author: "Thomas Edison" },
  { text: "Chase the vision, not the money; the money will end up following you.", author: "Tony Hsieh" },
  { text: "It's not about ideas. It's about making ideas happen.", author: "Scott Belsky" },
  { text: "If you can't fly, then run. If you can't run, then walk. If you can't walk, then crawl. But whatever you do, you have to keep moving forward.", author: "Martin Luther King Jr." },
  { text: "The only place where success comes before work is in the dictionary.", author: "Vidal Sassoon" },
  { text: "Make every detail perfect and limit the number of details to perfect.", author: "Jack Dorsey" },
  { text: "If you're not embarrassed by the first version of your product, you've launched too late.", author: "Reid Hoffman" },
  { text: "Your reputation is more important than your paycheck, and your integrity is worth more than your career.", author: "Ryan Freitas" },
  { text: "Every time you state what you want or believe, you're the first to hear it. It's a message to both you and others about what you think is possible.", author: "Oprah Winfrey" },
  { text: "The question isn't who is going to let me; it's who is going to stop me.", author: "Ayn Rand" },
  { text: "Innovation distinguishes between a leader and a follower.", author: "Steve Jobs" },
  { text: "There's no shortage of remarkable ideas, what's missing is the will to execute them.", author: "Seth Godin" },
  { text: "You don't need to have a 100-person company to develop that idea.", author: "Larry Page" },
  { text: "When everything seems to be going against you, remember that the airplane takes off against the wind, not with it.", author: "Henry Ford" },
  { text: "Don't be afraid to give up the good to go for the great.", author: "John D. Rockefeller" },
  { text: "Always deliver more than expected.", author: "Larry Page" },
  { text: "Risk more than others think is safe. Dream more than others think is practical.", author: "Howard Schultz" },
  { text: "The battles that count aren't the ones for gold medals. The struggles within yourself—the invisible, inevitable battles inside all of us—that's where it's at.", author: "Jesse Owens" },
  { text: "If you do build a great experience, customers tell each other about that. Word of mouth is very powerful.", author: "Jeff Bezos" },
  { text: "No matter how brilliant your mind or strategy, if you're playing a solo game, you'll always lose out to a team.", author: "Reid Hoffman" },
  { text: "If you want to achieve greatness stop asking for permission.", author: "Anonymous" },
  { text: "Things work out best for those who make the best of how things work out.", author: "John Wooden" },
  { text: "If you are not embarrassed by the first version of your product, you've launched too late.", author: "Reid Hoffman" }
];

// 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<TopProduct[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const { toast } = useToast()
  
  // Initialize with a random quote that's not Mark Twain
  const [randomQuote, setRandomQuote] = useState(getRandomQuote())
  
  const fetchTopProducts = async () => {
    try {
      setIsLoading(true)
      
      // Use clientFetch to handle URL routing and authentication properly
      const data = await clientFetch('/orders/top-products');
      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 (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-semibold text-foreground">
          {greeting}, {username}!
        </h1>
        <p className="text-muted-foreground mt-1 italic text-sm">
          "{randomQuote.text}" — <span className="font-medium">{randomQuote.author}</span>
        </p>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        {statsConfig.map((stat) => (
          <OrderStats
            key={stat.title}
            title={stat.title}
            value={orderStats[stat.key as keyof OrderStatsData].toLocaleString()}
            icon={stat.icon}
          />
        ))}
      </div>

      {/* Best Selling Products Section */}
      <div className="mt-8">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <div>
              <CardTitle>Your Best Selling Products</CardTitle>
              <CardDescription>Products with the highest sales from your store</CardDescription>
            </div>
            {error && (
              <Button 
                variant="outline" 
                size="sm" 
                onClick={fetchTopProducts}
                className="flex items-center gap-1"
              >
                <RefreshCcw className="h-3 w-3" />
                Retry
              </Button>
            )}
          </CardHeader>
          <CardContent>
            {isLoading ? (
              <div className="space-y-4">
                {[...Array(5)].map((_, i) => (
                  <div key={i} className="flex items-center gap-4">
                    <div className="h-12 w-12 rounded-md bg-muted animate-pulse"></div>
                    <div className="space-y-2 flex-1">
                      <div className="h-4 bg-muted rounded animate-pulse w-2/3"></div>
                      <div className="h-3 bg-muted rounded animate-pulse w-1/3"></div>
                    </div>
                    <div className="h-4 bg-muted rounded animate-pulse w-16"></div>
                  </div>
                ))}
              </div>
            ) : error ? (
              <div className="py-12 text-center text-muted-foreground">
                <p className="text-red-500 mb-2">Error loading products</p>
                <p className="text-sm">{error}</p>
              </div>
            ) : topProducts.length > 0 ? (
              <div className="space-y-4">
                {topProducts.map(product => (
                  <div key={product.id} className="flex items-center justify-between border-b pb-3">
                    <div className="flex items-center gap-3">
                      <div className="h-12 w-12 rounded-md bg-muted flex items-center justify-center">
                        {product.image ? (
                          <img 
                            src={`/api/products/${product.id}/image`} 
                            alt={product.name} 
                            className="h-10 w-10 object-cover rounded-md" 
                            onError={(e) => {
                              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);
                              }
                            }}
                          />
                        ) : (
                          <ShoppingCart className="h-5 w-5 text-muted-foreground" />
                        )}
                      </div>
                      <div>
                        <p className="font-medium">{product.name}</p>
                      </div>
                    </div>
                    <div className="text-right">
                      <p className="font-bold">{product.count} sold</p>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="py-12 text-center text-muted-foreground">
                <ShoppingCart className="mx-auto h-12 w-12 mb-4 text-muted" />
                <p>No sales data available yet</p>
                <p className="text-sm">Your best-selling products will appear here once you have orders</p>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  )
}

