"use client"

import { useEffect, useState } from "react"
import { getApiUrl } from "@/lib/api-config"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import Link from "next/link"
import { Star, Trophy, Users, MapPin, Music } from "lucide-react"

interface TopShow {
    show: {
        id: number
        date: string
        venue_id: number
    }
    avg_score: number
    review_count: number
}

interface TopVenue {
    venue: {
        id: number
        name: string
        city: string
        state: string
    }
    avg_score: number
    review_count: number
}

interface ActiveUser {
    profile: {
        id: number
        username: string
        display_name: string
    }
    review_count: number
}

export default function LeaderboardsPage() {
    const [topShows, setTopShows] = useState<TopShow[]>([])
    const [topVenues, setTopVenues] = useState<TopVenue[]>([])
    const [activeUsers, setActiveUsers] = useState<ActiveUser[]>([])
    const [loading, setLoading] = useState(true)

    useEffect(() => {
        const fetchData = async () => {
            try {
                const [showsRes, venuesRes, usersRes] = await Promise.all([
                    fetch(`${getApiUrl()}/leaderboards/shows/top`),
                    fetch(`${getApiUrl()}/leaderboards/venues/top`),
                    fetch(`${getApiUrl()}/leaderboards/users/active`)
                ])

                setTopShows(await showsRes.json())
                setTopVenues(await venuesRes.json())
                setActiveUsers(await usersRes.json())
            } catch (error) {
                console.error("Failed to fetch leaderboards:", error)
            } finally {
                setLoading(false)
            }
        }

        fetchData()
    }, [])

    if (loading) return <div className="container py-10">Loading leaderboards...</div>

    return (
        <div className="container py-10 space-y-8">
            <div className="flex flex-col gap-2">
                <h1 className="text-3xl font-bold tracking-tight">Leaderboards</h1>
                <p className="text-muted-foreground">
                    Top rated shows, venues, and our most active community members.
                </p>
            </div>

            <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
                {/* Top Shows */}
                <Card>
                    <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                            <Music className="h-5 w-5 text-blue-500" />
                            Top Rated Shows
                        </CardTitle>
                    </CardHeader>
                    <CardContent>
                        <div className="space-y-4">
                            {topShows.map((item, i) => (
                                <div key={item.show.id} className="flex items-center justify-between">
                                    <div className="flex items-center gap-3">
                                        <span className={`flex h-6 w-6 items-center justify-center rounded-full text-xs font-bold ${i === 0 ? "bg-yellow-100 text-yellow-700" :
                                                i === 1 ? "bg-gray-100 text-gray-700" :
                                                    i === 2 ? "bg-orange-100 text-orange-700" : "text-muted-foreground"
                                            }`}>
                                            {i + 1}
                                        </span>
                                        <Link href={`/shows/${item.show.id}`} className="font-medium hover:underline">
                                            {new Date(item.show.date).toLocaleDateString()}
                                        </Link>
                                    </div>
                                    <div className="flex items-center gap-1 text-sm">
                                        <Star className="h-3 w-3 fill-yellow-500 text-yellow-500" />
                                        <span className="font-bold">{item.avg_score}</span>
                                        <span className="text-muted-foreground text-xs">({item.review_count})</span>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </CardContent>
                </Card>

                {/* Top Venues */}
                <Card>
                    <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                            <MapPin className="h-5 w-5 text-green-500" />
                            Top Venues
                        </CardTitle>
                    </CardHeader>
                    <CardContent>
                        <div className="space-y-4">
                            {topVenues.map((item, i) => (
                                <div key={item.venue.id} className="flex items-center justify-between">
                                    <div className="flex items-center gap-3 overflow-hidden">
                                        <span className={`flex h-6 w-6 shrink-0 items-center justify-center rounded-full text-xs font-bold ${i === 0 ? "bg-yellow-100 text-yellow-700" :
                                                i === 1 ? "bg-gray-100 text-gray-700" :
                                                    i === 2 ? "bg-orange-100 text-orange-700" : "text-muted-foreground"
                                            }`}>
                                            {i + 1}
                                        </span>
                                        <Link href={`/venues/${item.venue.id}`} className="font-medium hover:underline truncate">
                                            {item.venue.name}
                                        </Link>
                                    </div>
                                    <div className="flex items-center gap-1 text-sm shrink-0">
                                        <Star className="h-3 w-3 fill-yellow-500 text-yellow-500" />
                                        <span className="font-bold">{item.avg_score}</span>
                                        <span className="text-muted-foreground text-xs">({item.review_count})</span>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </CardContent>
                </Card>

                {/* Active Users */}
                <Card>
                    <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                            <Users className="h-5 w-5 text-purple-500" />
                            Most Active Fans
                        </CardTitle>
                    </CardHeader>
                    <CardContent>
                        <div className="space-y-4">
                            {activeUsers.map((item, i) => (
                                <div key={item.profile.id} className="flex items-center justify-between">
                                    <div className="flex items-center gap-3">
                                        <span className={`flex h-6 w-6 items-center justify-center rounded-full text-xs font-bold ${i === 0 ? "bg-yellow-100 text-yellow-700" :
                                                i === 1 ? "bg-gray-100 text-gray-700" :
                                                    i === 2 ? "bg-orange-100 text-orange-700" : "text-muted-foreground"
                                            }`}>
                                            {i + 1}
                                        </span>
                                        <Link href={`/users/${item.profile.id}`} className="font-medium hover:underline">
                                            {item.profile.display_name || item.profile.username}
                                        </Link>
                                    </div>
                                    <div className="text-sm">
                                        <span className="font-bold">{item.review_count}</span>
                                        <span className="text-muted-foreground text-xs ml-1">reviews</span>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </CardContent>
                </Card>
            </div>
        </div>
    )
}
