"use client"

import { useEffect, useState, Suspense } from "react"
import { getApiUrl } from "@/lib/api-config"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import Link from "next/link"
import { Calendar, MapPin, Loader2, Youtube } from "lucide-react"
import { Skeleton } from "@/components/ui/skeleton"
import { useSearchParams } from "next/navigation"
import { Button } from "@/components/ui/button"

interface Show {
    id: number
    slug?: string
    date: string
    youtube_link?: string
    venue: {
        id: number
        name: string
        city: string
        state: string
    }
}

function ShowsContent() {
    const searchParams = useSearchParams()
    const year = searchParams.get("year")

    const [shows, setShows] = useState<Show[]>([])
    const [loading, setLoading] = useState(true)

    useEffect(() => {
        const url = `${getApiUrl()}/shows/?limit=2000&status=past${year ? `&year=${year}` : ''}`
        fetch(url)
            .then(res => res.json())
            .then(data => {
                // Sort by date descending
                const sorted = data.sort((a: Show, b: Show) =>
                    new Date(b.date).getTime() - new Date(a.date).getTime()
                )
                setShows(sorted)
            })
            .catch(console.error)
            .finally(() => setLoading(false))
    }, [year])

    if (loading) {
        return (
            <div className="container py-10 space-y-8">
                <div className="flex flex-col gap-2">
                    <Skeleton className="h-10 w-48" />
                    <Skeleton className="h-5 w-96" />
                </div>

                <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
                    {Array.from({ length: 12 }).map((_, i) => (
                        <Card key={i} className="h-full border-muted/40">
                            <CardHeader>
                                <div className="flex items-center gap-2">
                                    <Skeleton className="h-5 w-5 rounded-full" />
                                    <Skeleton className="h-5 w-3/4" />
                                </div>
                            </CardHeader>
                            <CardContent>
                                <div className="flex items-center gap-2">
                                    <Skeleton className="h-4 w-4 rounded-full" />
                                    <Skeleton className="h-4 w-1/2" />
                                </div>
                            </CardContent>
                        </Card>
                    ))}
                </div>
            </div>
        )
    }

    return (
        <div className="container py-10 space-y-8 animate-in fade-in duration-700">
            <div className="flex flex-col gap-2">
                <div className="flex justify-between items-start">
                    <div>
                        <h1 className="text-3xl font-bold tracking-tight">Shows</h1>
                        <p className="text-muted-foreground">
                            Browse the complete archive of performances.
                        </p>
                    </div>
                    <Link href="/shows/upcoming">
                        <Button variant="outline" className="gap-2">
                            <Calendar className="h-4 w-4" />
                            Upcoming Shows
                        </Button>
                    </Link>
                </div>
            </div>

            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
                {shows.map((show) => (
                    <Link key={show.id} href={`/shows/${show.slug}`} className="block group">
                        <Card className="h-full transition-all duration-300 hover:scale-[1.02] hover:shadow-lg group-hover:border-primary/50 relative">
                            {show.youtube_link && (
                                <div className="absolute top-2 right-2 bg-red-500/10 text-red-500 p-1.5 rounded-full" title="Full show video available">
                                    <Youtube className="h-4 w-4" />
                                </div>
                            )}
                            <CardHeader>
                                <CardTitle className="flex items-center gap-2 group-hover:text-primary transition-colors">
                                    <Calendar className="h-5 w-5 text-muted-foreground group-hover:text-primary/70 transition-colors" />
                                    {new Date(show.date).toLocaleDateString(undefined, {
                                        weekday: 'long',
                                        year: 'numeric',
                                        month: 'long',
                                        day: 'numeric'
                                    })}
                                </CardTitle>
                            </CardHeader>
                            <CardContent>
                                <div className="flex items-center gap-2 text-muted-foreground group-hover:text-foreground transition-colors">
                                    <MapPin className="h-4 w-4" />
                                    <span>
                                        {show.venue?.name}, {show.venue?.city}, {show.venue?.state}
                                    </span>
                                </div>
                            </CardContent>
                        </Card>
                    </Link>
                ))}
            </div>
        </div>
    )
}

function LoadingFallback() {
    return (
        <div className="container py-10 flex items-center justify-center min-h-[400px]">
            <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
        </div>
    )
}

export default function ShowsPage() {
    return (
        <Suspense fallback={<LoadingFallback />}>
            <ShowsContent />
        </Suspense>
    )
}
