"use client"

import { useEffect, useState } 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 } from "lucide-react"

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

export default function ShowsPage() {
    const [shows, setShows] = useState<Show[]>([])
    const [loading, setLoading] = useState(true)

    useEffect(() => {
        fetch(`${getApiUrl()}/shows/?limit=50`)
            .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))
    }, [])

    if (loading) return <div className="container py-10">Loading shows...</div>

    return (
        <div className="container py-10 space-y-8">
            <div className="flex flex-col gap-2">
                <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="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
                {shows.map((show) => (
                    <Link key={show.id} href={`/shows/${show.id}`}>
                        <Card className="h-full hover:bg-accent/50 transition-colors">
                            <CardHeader>
                                <CardTitle className="flex items-center gap-2">
                                    <Calendar className="h-5 w-5 text-muted-foreground" />
                                    {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">
                                    <MapPin className="h-4 w-4" />
                                    <span>
                                        {show.venue?.name}, {show.venue?.city}, {show.venue?.state}
                                    </span>
                                </div>
                            </CardContent>
                        </Card>
                    </Link>
                ))}
            </div>
        </div>
    )
}
