import { notFound } from "next/navigation"
import { VERTICALS } from "@/config/verticals"
import { getApiUrl } from "@/lib/api-config"
import Link from "next/link"
import { Calendar, MapPin, Music, Trophy, Video, Ticket, Building, ChevronRight, Play } from "lucide-react"
import { Card, CardContent } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { VideoGallery } from "@/components/videos/video-gallery"

interface Props {
    params: Promise<{ vertical: string }>
}

export function generateStaticParams() {
    return VERTICALS.map((v) => ({
        vertical: v.slug,
    }))
}

async function getRecentShows(verticalSlug: string) {
    try {
        const res = await fetch(`${getApiUrl()}/shows/?vertical_slugs=${verticalSlug}&limit=8&status=past`, {
            next: { revalidate: 60 }
        })
        if (!res.ok) return []
        return res.json()
    } catch {
        return []
    }
}

async function getTopSongs(verticalSlug: string) {
    try {
        const res = await fetch(`${getApiUrl()}/songs/?vertical=${verticalSlug}&limit=5&sort=times_played`, {
            next: { revalidate: 60 }
        })
        if (!res.ok) return []
        return res.json()
    } catch {
        return []
    }
}

export default async function VerticalPage({ params }: Props) {
    const { vertical: verticalSlug } = await params
    const vertical = VERTICALS.find((v) => v.slug === verticalSlug)

    if (!vertical) {
        notFound()
    }

    const [recentShows, topSongs] = await Promise.all([
        getRecentShows(verticalSlug),
        getTopSongs(verticalSlug)
    ])

    const navCards = [
        { href: `/${verticalSlug}/shows`, icon: Calendar, title: "Shows", desc: "Browse the complete archive" },
        { href: `/${verticalSlug}/venues`, icon: Building, title: "Venues", desc: "Find your favorite spots" },
        { href: `/${verticalSlug}/songs`, icon: Music, title: "Songs", desc: "Explore the catalog" },
        { href: `/${verticalSlug}/performances`, icon: Trophy, title: "Top Performances", desc: "Highest rated jams" },
        { href: `/leaderboards?band=${verticalSlug}`, icon: Trophy, title: "Leaderboards", desc: "Top rated everything" },
        { href: `/${verticalSlug}/tours`, icon: Ticket, title: "Tours", desc: "Browse by tour" },
        { href: `/videos?band=${verticalSlug}`, icon: Video, title: "Videos", desc: "Watch full shows and songs" },
    ]

    return (
        <div className="space-y-12 pb-12">
            {/* Hero Section */}
            <section className="relative py-16 md:py-24 text-center space-y-6 bg-gradient-to-b from-primary/5 to-transparent">
                <h1 className="text-5xl md:text-6xl font-bold tracking-tight bg-gradient-to-r from-primary to-primary/60 bg-clip-text text-transparent">
                    {vertical.name}
                </h1>
                <p className="text-xl text-muted-foreground max-w-2xl mx-auto px-4">
                    A comprehensive community-driven archive for {vertical.name} history.
                    <br className="hidden sm:block" />
                    Discover shows, share ratings, and explore the music together.
                </p>
                <div className="flex flex-wrap justify-center gap-4 pt-4">
                    <Link href={`/${verticalSlug}/performances`}>
                        <Button size="lg" className="gap-2">
                            <Trophy className="h-4 w-4" />
                            Top Performances
                        </Button>
                    </Link>
                    <Link href={`/${verticalSlug}/shows`}>
                        <Button size="lg" variant="outline" className="gap-2">
                            <Calendar className="h-4 w-4" />
                            Browse Shows
                        </Button>
                    </Link>
                </div>
            </section>

            <div className="container max-w-6xl space-y-12 px-4">
                {/* Recent Shows */}
                {recentShows.length > 0 && (
                    <section className="space-y-4">
                        <div className="flex items-center justify-between">
                            <h2 className="text-2xl font-bold tracking-tight">Recent Shows</h2>
                            <Link href={`/${verticalSlug}/shows`} className="text-sm text-muted-foreground hover:text-primary transition-colors flex items-center gap-1">
                                View all shows <ChevronRight className="h-4 w-4" />
                            </Link>
                        </div>
                        <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
                            {recentShows.slice(0, 8).map((show: any) => (
                                <Link
                                    key={show.id}
                                    href={`/${verticalSlug}/shows/${show.slug}`}
                                    className="group"
                                >
                                    <Card className="h-full transition-all duration-200 hover:scale-[1.02] hover:shadow-lg hover:border-primary/50">
                                        <CardContent className="p-4 space-y-2">
                                            <div className="text-sm font-medium text-primary">
                                                {new Date(show.date).toLocaleDateString('en-US', {
                                                    weekday: 'short',
                                                    month: 'short',
                                                    day: 'numeric',
                                                    year: 'numeric'
                                                })}
                                            </div>
                                            <div className="font-semibold group-hover:text-primary transition-colors line-clamp-1">
                                                {show.venue?.name || "Unknown Venue"}
                                            </div>
                                            <div className="text-sm text-muted-foreground flex items-center gap-1">
                                                <MapPin className="h-3 w-3" />
                                                {show.venue?.city}, {show.venue?.state || show.venue?.country}
                                            </div>
                                            {show.tour?.name && (
                                                <div className="text-xs text-muted-foreground/80 pt-1">
                                                    {show.tour.name}
                                                </div>
                                            )}
                                        </CardContent>
                                    </Card>
                                </Link>
                            ))}
                        </div>
                    </section>
                )}

                {/* Top Songs */}
                {topSongs.length > 0 && (
                    <section className="space-y-4">
                        <div className="flex items-center justify-between">
                            <h2 className="text-2xl font-bold tracking-tight">Top Songs</h2>
                            <Link href={`/${verticalSlug}/songs`} className="text-sm text-muted-foreground hover:text-primary transition-colors flex items-center gap-1">
                                All songs <ChevronRight className="h-4 w-4" />
                            </Link>
                        </div>
                        <div className="space-y-2">
                            {topSongs.slice(0, 5).map((song: any, index: number) => (
                                <Link
                                    key={song.id}
                                    href={`/${verticalSlug}/songs/${song.slug}`}
                                    className="group"
                                >
                                    <div className="flex items-center gap-4 p-3 rounded-lg border bg-card hover:bg-accent/50 transition-all duration-200">
                                        <div className="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-sm font-bold text-primary">
                                            {index + 1}
                                        </div>
                                        <div className="flex-1 min-w-0">
                                            <div className="font-medium group-hover:text-primary transition-colors truncate">
                                                {song.title}
                                            </div>
                                        </div>
                                        <div className="text-sm text-muted-foreground whitespace-nowrap">
                                            {song.times_played || song.performance_count || 0} performances
                                        </div>
                                    </div>
                                </Link>
                            ))}
                        </div>
                    </section>
                )}

                {/* Videos Section */}
                <section className="space-y-4">
                    <VideoGallery
                        bandSlug={verticalSlug}
                        limit={8}
                        title="Recent Videos"
                    />
                </section>

                {/* Navigation Cards */}
                <section className="space-y-4">
                    <h2 className="text-2xl font-bold tracking-tight">Explore</h2>
                    <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
                        {navCards.map((card) => (
                            <Link key={card.href} href={card.href} className="group">
                                <Card className="h-full transition-all duration-200 hover:scale-[1.02] hover:shadow-lg hover:border-primary/50">
                                    <CardContent className="p-6 flex items-start gap-4">
                                        <div className="p-3 rounded-lg bg-primary/10 text-primary group-hover:bg-primary group-hover:text-primary-foreground transition-colors">
                                            <card.icon className="h-5 w-5" />
                                        </div>
                                        <div>
                                            <h3 className="font-semibold group-hover:text-primary transition-colors">
                                                {card.title}
                                            </h3>
                                            <p className="text-sm text-muted-foreground">
                                                {card.desc}
                                            </p>
                                        </div>
                                    </CardContent>
                                </Card>
                            </Link>
                        ))}
                    </div>
                </section>
            </div>
        </div>
    )
}
