"use client"

import { useEffect, useState, Suspense, useMemo } from "react"
import { getApiUrl } from "@/lib/api-config"
import { Loader2, Calendar } from "lucide-react"
import { Skeleton } from "@/components/ui/skeleton"
import { useSearchParams } from "next/navigation"
import { Button } from "@/components/ui/button"
import Link from "next/link"
import { BandFilter } from "@/components/shows/band-filter"
import { DateGroupedList } from "@/components/shows/date-grouped-list"

interface Show {
    id: number
    slug?: string
    date: string
    youtube_link?: string
    vertical?: {
        name: string
        slug: 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)
    const [selectedBands, setSelectedBands] = useState<string[]>([])

    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])

    // Filter shows locally based on selection
    const filteredShows = useMemo(() => {
        if (selectedBands.length === 0) return shows
        return shows.filter(show =>
            show.vertical && selectedBands.includes(show.vertical.slug)
        )
    }, [shows, selectedBands])

    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) => (
                        <Skeleton key={i} className="h-32 w-full rounded-lg" />
                    ))}
                </div>
            </div>
        )
    }

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

            <DateGroupedList shows={filteredShows} />
        </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>
    )
}
