"use client"

import { useEffect, useState } from "react"
import { getApiUrl } from "@/lib/api-config"
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import Link from "next/link"
import { Star, MapPin, Music, User, Trophy, Calendar, Sparkles } from "lucide-react"
import { Badge } from "@/components/ui/badge"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { motion, AnimatePresence } from "framer-motion"

interface TopShow {
    show: { id: number; date: string; venue_id: number }
    venue: { id: number; name: string; city: string; state: string }
    avg_score: number
    review_count: number
}

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

interface TopPerformance {
    performance: { id: number; show_id: number; song_id: number; notes: string | null }
    song: { id: number; title: string; original_artist: string | null }
    show: { id: number; date: string }
    venue: { id: number; name: string; city: string; state: string }
    avg_score: number
    rating_count: number
}

interface TopUser {
    profile: { id: number; user_id: number }
    review_count: number
}

export default function LeaderboardsPage() {
    const [topShows, setTopShows] = useState<TopShow[]>([])
    const [topVenues, setTopVenues] = useState<TopVenue[]>([])
    const [topPerformances, setTopPerformances] = useState<TopPerformance[]>([])
    const [topUsers, setTopUsers] = useState<TopUser[]>([])
    const [loading, setLoading] = useState(true)

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

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

        fetchData()
    }, [])

    const RankIcon = ({ rank }: { rank: number }) => {
        if (rank === 1) return <Trophy className="h-5 w-5 text-yellow-500" />
        if (rank === 2) return <Trophy className="h-4 w-4 text-gray-400" />
        if (rank === 3) return <Trophy className="h-4 w-4 text-orange-400" />
        return <span className="text-muted-foreground font-mono w-5 text-center">{rank}</span>
    }

    if (loading) {
        return (
            <div className="container py-10 flex items-center justify-center min-h-[50vh]">
                <div className="flex flex-col items-center gap-4">
                    <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
                    <p className="text-muted-foreground animate-pulse">Computing Heady Stats...</p>
                </div>
            </div>
        )
    }

    return (
        <div className="container py-10 space-y-8 max-w-5xl">
            <motion.div
                initial={{ opacity: 0, y: -20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.5 }}
                className="flex flex-col gap-2"
            >
                <h1 className="text-4xl font-bold tracking-tight bg-gradient-to-r from-primary to-primary/60 bg-clip-text text-transparent">
                    Leaderboards
                </h1>
                <p className="text-xl text-muted-foreground">
                    Discover the highest rated shows, legendary jams, and top contributors.
                </p>
            </motion.div>

            <Tabs defaultValue="jams" className="w-full">
                <TabsList className="grid w-full grid-cols-4 mb-8 h-12">
                    <TabsTrigger value="jams" className="text-base font-medium">Heady Jams</TabsTrigger>
                    <TabsTrigger value="shows" className="text-base font-medium">Top Shows</TabsTrigger>
                    <TabsTrigger value="venues" className="text-base font-medium">Venues</TabsTrigger>
                    <TabsTrigger value="users" className="text-base font-medium">Contributors</TabsTrigger>
                </TabsList>

                {/* HEADY JAMS CONTENT */}
                <TabsContent value="jams">
                    <motion.div
                        initial={{ opacity: 0, x: -10 }}
                        animate={{ opacity: 1, x: 0 }}
                        transition={{ duration: 0.2 }}
                    >
                        <Card className="border-none shadow-none bg-transparent">
                            <div className="grid gap-4">
                                {topPerformances.map((item, i) => (
                                    <motion.div
                                        key={item.performance.id}
                                        initial={{ opacity: 0, y: 10 }}
                                        animate={{ opacity: 1, y: 0 }}
                                        transition={{ delay: i * 0.05 }}
                                        className="group relative flex items-center gap-4 rounded-xl border bg-card p-4 shadow-sm transition-all hover:shadow-md hover:border-primary/50"
                                    >
                                        <div className="flex h-12 w-12 items-center justify-center rounded-full bg-secondary/50 font-bold text-xl">
                                            <RankIcon rank={i + 1} />
                                        </div>
                                        <div className="flex flex-1 flex-col justify-center gap-1">
                                            <div className="flex items-center gap-2">
                                                <Link href={`/songs/${item.song.id}`} className="font-semibold text-lg hover:underline decoration-primary decoration-2 underline-offset-2">
                                                    {item.song.title}
                                                </Link>
                                                {item.performance.notes && (
                                                    <Badge variant="outline" className="text-[10px] font-normal hidden sm:inline-flex">
                                                        {item.performance.notes}
                                                    </Badge>
                                                )}
                                            </div>
                                            <div className="flex items-center text-sm text-muted-foreground gap-2">
                                                <Calendar className="h-3 w-3" />
                                                <Link href={`/shows/${item.show.id}`} className="hover:text-primary transition-colors">
                                                    {new Date(item.show.date).toLocaleDateString(undefined, {
                                                        weekday: 'short', year: 'numeric', month: 'short', day: 'numeric'
                                                    })}
                                                </Link>
                                                <span className="text-muted-foreground/50">•</span>
                                                <span className="truncate max-w-[200px]">{item.venue.name}</span>
                                            </div>
                                        </div>
                                        <div className="flex flex-col items-end justify-center min-w-[80px]">
                                            <div className="flex items-center gap-1.5">
                                                <Star className="h-4 w-4 fill-yellow-500 text-yellow-500" />
                                                <span className="text-xl font-bold">{item.avg_score.toFixed(2)}</span>
                                            </div>
                                            <span className="text-xs text-muted-foreground">{item.rating_count} votes</span>
                                        </div>
                                    </motion.div>
                                ))}
                                {topPerformances.length === 0 && (
                                    <div className="text-center py-12 text-muted-foreground">
                                        No ranked jams yet. Start rating performances!
                                    </div>
                                )}
                            </div>
                        </Card>
                    </motion.div>
                </TabsContent>

                {/* TOP SHOWS CONTENT */}
                <TabsContent value="shows">
                    <motion.div
                        initial={{ opacity: 0, x: -10 }}
                        animate={{ opacity: 1, x: 0 }}
                        transition={{ duration: 0.2 }}
                        className="grid gap-4"
                    >
                        {topShows.map((item, i) => (
                            <motion.div
                                key={item.show.id}
                                initial={{ opacity: 0, y: 10 }}
                                animate={{ opacity: 1, y: 0 }}
                                transition={{ delay: i * 0.05 }}
                                className="flex items-center justify-between p-4 rounded-lg border bg-card hover:bg-accent/50 transition-colors"
                            >
                                <div className="flex items-center gap-4">
                                    <div className="font-mono text-muted-foreground w-6 text-center">{i + 1}</div>
                                    <div>
                                        <Link href={`/shows/${item.show.id}`} className="font-medium text-lg hover:underline block">
                                            {new Date(item.show.date).toLocaleDateString(undefined, {
                                                year: 'numeric', month: 'long', day: 'numeric'
                                            })}
                                        </Link>
                                        <p className="text-sm text-muted-foreground">
                                            {item.venue.name} • {item.venue.city}, {item.venue.state}
                                        </p>
                                    </div>
                                </div>
                                <div className="text-right">
                                    <div className="font-bold text-lg flex items-center justify-end gap-1">
                                        <Star className="h-4 w-4 fill-primary/20 text-primary" />
                                        {item.avg_score.toFixed(2)}
                                    </div>
                                    <div className="text-xs text-muted-foreground">{item.review_count} ratings</div>
                                </div>
                            </motion.div>
                        ))}
                    </motion.div>
                </TabsContent>

                {/* VENUES CONTENT */}
                <TabsContent value="venues">
                    <motion.div
                        initial={{ opacity: 0, x: -10 }}
                        animate={{ opacity: 1, x: 0 }}
                        transition={{ duration: 0.2 }}
                        className="grid gap-4 md:grid-cols-2"
                    >
                        {topVenues.map((item, i) => (
                            <motion.div
                                key={item.venue.id}
                                initial={{ opacity: 0, scale: 0.95 }}
                                animate={{ opacity: 1, scale: 1 }}
                                transition={{ delay: i * 0.05 }}
                                className="flex items-center justify-between p-4 rounded-lg border bg-card/50"
                            >
                                <div className="flex items-center gap-3 overflow-hidden">
                                    <div className={`
                                        flex h-8 w-8 items-center justify-center rounded-full text-sm font-bold shrink-0
                                        ${i < 3 ? 'bg-primary/10 text-primary' : 'bg-muted text-muted-foreground'}
                                     `}>
                                        {i + 1}
                                    </div>
                                    <div>
                                        <Link href={`/venues/${item.venue.id}`} className="font-medium hover:underline truncate block">
                                            {item.venue.name}
                                        </Link>
                                        <p className="text-xs text-muted-foreground truncate">
                                            {item.venue.city}, {item.venue.state}
                                        </p>
                                    </div>
                                </div>
                                <Badge variant="secondary" className="gap-1 ml-2 shrink-0">
                                    <Star className="h-3 w-3 fill-current" />
                                    {item.avg_score.toFixed(2)}
                                </Badge>
                            </motion.div>
                        ))}
                    </motion.div>
                </TabsContent>

                {/* USERS CONTENT */}
                <TabsContent value="users">
                    <motion.div
                        initial={{ opacity: 0, x: -10 }}
                        animate={{ opacity: 1, x: 0 }}
                        transition={{ duration: 0.2 }}
                        className="grid gap-4 md:grid-cols-3"
                    >
                        {topUsers.map((item, i) => (
                            <motion.div
                                key={item.profile.id}
                                initial={{ opacity: 0, y: 10 }}
                                animate={{ opacity: 1, y: 0 }}
                                transition={{ delay: i * 0.05 }}
                            >
                                <Card className="flex flex-col items-center justify-center p-6 text-center hover:border-primary/50 transition-colors h-full">
                                    <Avatar className="h-16 w-16 mb-4">
                                        <AvatarImage src={`https://api.dicebear.com/7.x/notionists/svg?seed=${item.profile.user_id}`} />
                                        <AvatarFallback>U</AvatarFallback>
                                    </Avatar>
                                    <div className="font-semibold text-lg">User {item.profile.user_id}</div>
                                    <p className="text-sm text-muted-foreground mb-3">Top Contributor</p>
                                    <Badge variant="outline" className="bg-primary/5">
                                        {item.review_count} Reviews
                                    </Badge>
                                </Card>
                            </motion.div>
                        ))}
                        {topUsers.length === 0 && <p className="col-span-3 text-center text-muted-foreground py-10">No active users yet.</p>}
                    </motion.div>
                </TabsContent>
            </Tabs>
        </div>
    )
}
