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 } from "lucide-react"
import { Card, CardContent } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from "@/components/ui/table"
import { Show, Song, PaginatedResponse } from "@/types/models"

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

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

async function getRecentShows(verticalSlug: string): Promise<Show[]> {
    try {
        // Fetch 10 recent shows
        const res = await fetch(`${getApiUrl()}/shows/?vertical_slugs=${verticalSlug}&limit=10&status=past`, {
            next: { revalidate: 60 }
        })
        if (!res.ok) return []
        const data: PaginatedResponse<Show> = await res.json()
        return data.data || []
    } catch {
        return []
    }
}

async function getTopSongs(verticalSlug: string): Promise<Song[]> {
    try {
        // Fetch top 10 songs, assuming backend now populates times_played
        const res = await fetch(`${getApiUrl()}/songs/?vertical=${verticalSlug}&limit=10&sort=times_played`, {
            next: { revalidate: 60 }
        })
        if (!res.ok) return []
        const data: PaginatedResponse<Song> = await res.json()
        return data.data || []
    } catch {
        return []
    }
}

async function getVerticalStats(verticalSlug: string) {
    try {
        const res = await fetch(`${getApiUrl()}/bands/${verticalSlug}`, {
            next: { revalidate: 300 }
        })
        if (!res.ok) return null
        return res.json()
    } catch {
        return null
    }
}

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, bandProfile] = await Promise.all([
        getRecentShows(verticalSlug),
        getTopSongs(verticalSlug),
        getVerticalStats(verticalSlug)
    ])

    const stats = bandProfile?.stats || {}

    return (
        <div className="space-y-8 pb-12">
            {/* Hero Section - Compact & Utilitarian */}
            <section className="bg-muted/30 border-b">
                <div className="container py-8 px-4">
                    <div className="flex flex-col md:flex-row md:items-center justify-between gap-6">
                        <div className="space-y-2">
                            <h1 className="text-4xl font-bold tracking-tight">{vertical.name}</h1>
                            <p className="text-muted-foreground max-w-2xl text-lg">
                                {vertical.description}
                            </p>
                        </div>

                        {/* High-Level Stats */}
                        <div className="grid grid-cols-3 gap-8 text-center md:text-right">
                            <div>
                                <div className="text-3xl font-bold">{stats.total_shows || 0}</div>
                                <div className="text-sm text-muted-foreground font-medium uppercase tracking-wider">Shows</div>
                            </div>
                            <div>
                                <div className="text-3xl font-bold">{stats.total_songs || 0}</div>
                                <div className="text-sm text-muted-foreground font-medium uppercase tracking-wider">Songs</div>
                            </div>
                            <div>
                                <div className="text-3xl font-bold">{stats.total_venues || 0}</div>
                                <div className="text-sm text-muted-foreground font-medium uppercase tracking-wider">Venues</div>
                            </div>
                        </div>
                    </div>

                    {/* Quick Actions Bar */}
                    <div className="flex flex-wrap gap-2 mt-8">
                        <Link href={`/${verticalSlug}/shows`}>
                            <Button variant="outline" size="sm" className="gap-2">
                                <Calendar className="h-4 w-4" /> Shows
                            </Button>
                        </Link>
                        <Link href={`/${verticalSlug}/songs`}>
                            <Button variant="outline" size="sm" className="gap-2">
                                <Music className="h-4 w-4" /> Songs
                            </Button>
                        </Link>
                        <Link href={`/${verticalSlug}/venues`}>
                            <Button variant="outline" size="sm" className="gap-2">
                                <MapPin className="h-4 w-4" /> Venues
                            </Button>
                        </Link>
                        <Link href={`/${verticalSlug}/performances`}>
                            <Button variant="outline" size="sm" className="gap-2">
                                <Trophy className="h-4 w-4" /> Top Rated
                            </Button>
                        </Link>
                        <Link href={`/videos?band=${verticalSlug}`}>
                            <Button variant="outline" size="sm" className="gap-2">
                                <Video className="h-4 w-4" /> Videos
                            </Button>
                        </Link>
                    </div>
                </div>
            </section>

            <div className="container px-4 space-y-12">
                <div className="grid gap-8 lg:grid-cols-2">
                    {/* Recent Shows Table */}
                    <div 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`}>
                                <Button variant="ghost" size="sm" className="gap-1">
                                    View All <ChevronRight className="h-4 w-4" />
                                </Button>
                            </Link>
                        </div>

                        <Card>
                            <Table>
                                <TableHeader>
                                    <TableRow>
                                        <TableHead>Date</TableHead>
                                        <TableHead>Venue</TableHead>
                                        <TableHead className="text-right">Location</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {recentShows.length === 0 ? (
                                        <TableRow>
                                            <TableCell colSpan={3} className="text-center h-24 text-muted-foreground">
                                                No shows found
                                            </TableCell>
                                        </TableRow>
                                    ) : (
                                        recentShows.map((show) => (
                                            <TableRow key={show.id}>
                                                <TableCell className="font-medium whitespace-nowrap">
                                                    <Link href={`/${verticalSlug}/shows/${show.slug}`} className="hover:underline text-primary">
                                                        {new Date(show.date).toLocaleDateString('en-US', {
                                                            month: 'short', day: 'numeric', year: 'numeric'
                                                        })}
                                                    </Link>
                                                </TableCell>
                                                <TableCell>
                                                    <span className="line-clamp-1">{show.venue?.name || "Unknown"}</span>
                                                </TableCell>
                                                <TableCell className="text-right text-muted-foreground">
                                                    {show.venue?.city}, {show.venue?.state}
                                                </TableCell>
                                            </TableRow>
                                        ))
                                    )}
                                </TableBody>
                            </Table>
                        </Card>
                    </div>

                    {/* Most Played Songs Table */}
                    <div className="space-y-4">
                        <div className="flex items-center justify-between">
                            <h2 className="text-2xl font-bold tracking-tight">Most Played Songs</h2>
                            <Link href={`/${verticalSlug}/songs`}>
                                <Button variant="ghost" size="sm" className="gap-1">
                                    View Catalog <ChevronRight className="h-4 w-4" />
                                </Button>
                            </Link>
                        </div>

                        <Card>
                            <Table>
                                <TableHeader>
                                    <TableRow>
                                        <TableHead>Title</TableHead>
                                        <TableHead className="text-right">Plays</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {topSongs.length === 0 ? (
                                        <TableRow>
                                            <TableCell colSpan={2} className="text-center h-24 text-muted-foreground">
                                                No songs found
                                            </TableCell>
                                        </TableRow>
                                    ) : (
                                        topSongs.map((song) => (
                                            <TableRow key={song.id}>
                                                <TableCell className="font-medium">
                                                    <Link href={`/${verticalSlug}/songs/${song.slug}`} className="hover:underline text-primary">
                                                        {song.title}
                                                    </Link>
                                                    {song.original_artist && (
                                                        <span className="ml-2 text-xs text-muted-foreground">
                                                            by {song.original_artist}
                                                        </span>
                                                    )}
                                                </TableCell>
                                                <TableCell className="text-right">
                                                    <Badge variant="secondary">{song.times_played || 0}</Badge>
                                                </TableCell>
                                            </TableRow>
                                        ))
                                    )}
                                </TableBody>
                            </Table>
                        </Card>
                    </div>
                </div>
            </div>
        </div>
    )
}
