"use client"

import { useEffect, useState } from "react"
import { useParams } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { ArrowLeft, MapPin, Calendar, Music, Star } from "lucide-react"
import Link from "next/link"
import { getApiUrl } from "@/lib/api-config"

interface Venue {
    id: number
    name: string
    city: string
    state: string
    country: string
    capacity: number | null
    notes: string | null
}

interface Show {
    id: number
    slug?: string
    date: string
    tour?: { name: string }
    vertical?: { name: string; slug: string }
    performances?: any[]
}

// ... (skipping to render loop)

{
    shows.map((show) => (
        <Link
            key={show.id}
            href={show.vertical ? `/${show.vertical.slug}/shows/${show.slug}` : `/shows/${show.slug}`}
            className="block group"
        >
            <div className="flex items-center justify-between p-4 rounded-lg border bg-card hover:bg-accent transition-colors">
                <div className="space-y-1">
                    <div className="font-semibold flex items-center gap-2">
                        <Calendar className="h-4 w-4 text-muted-foreground" />
                        <span>{new Date(show.date).toLocaleDateString(undefined, {
                            weekday: 'long',
                            year: 'numeric',
                            month: 'long',
                            day: 'numeric'
                        })}</span>
                        {show.vertical && (
                            <span className="inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 border-transparent bg-primary text-primary-foreground hover:bg-primary/80 ml-2">
                                {show.vertical.name}
                            </span>
                        )}
                    </div>
                    {show.tour?.name && (
                        <div className="text-sm text-muted-foreground ml-6">
                            {show.tour.name}
                        </div>
                    )}
                </div>
                <div className="text-right text-sm text-muted-foreground">
                    {show.performances?.length || 0} songs
                </div>
            </div>
        </Link>
    ))
}

export default function VenueDetailPage() {
    const params = useParams()
    const slug = params.slug as string

    const [venue, setVenue] = useState<Venue | null>(null)
    const [shows, setShows] = useState<Show[]>([])
    const [loading, setLoading] = useState(true)
    const [error, setError] = useState<string | null>(null)

    useEffect(() => {
        async function fetchData() {
            try {
                // Fetch venue
                const venueRes = await fetch(`${getApiUrl()}/venues/${slug}`)
                if (!venueRes.ok) {
                    if (venueRes.status === 404) {
                        setError("Venue not found")
                    } else {
                        setError("Failed to load venue")
                    }
                    return
                }
                const venueData = await venueRes.json()
                setVenue(venueData)

                // Fetch shows at this venue using numeric ID
                const showsRes = await fetch(`${getApiUrl()}/shows/?venue_id=${venueData.id}&limit=100`)
                if (showsRes.ok) {
                    const showsEnvelope = await showsRes.json()
                    const showsData = showsEnvelope.data || []
                    // Sort by date descending
                    showsData.sort((a: Show, b: Show) =>
                        new Date(b.date).getTime() - new Date(a.date).getTime()
                    )
                    setShows(showsData)
                }
            } catch (err) {
                console.error("Error fetching venue:", err)
                setError("Failed to load venue")
            } finally {
                setLoading(false)
            }
        }
        fetchData()
    }, [slug])

    if (loading) {
        return (
            <div className="container py-10">
                <div className="animate-pulse space-y-6">
                    <div className="h-8 bg-muted rounded w-64" />
                    <div className="h-4 bg-muted rounded w-48" />
                    <div className="h-64 bg-muted rounded" />
                </div>
            </div>
        )
    }

    if (error || !venue) {
        return (
            <div className="container py-10">
                <div className="text-center py-12">
                    <MapPin className="h-12 w-12 mx-auto mb-4 text-muted-foreground" />
                    <h1 className="text-2xl font-bold mb-2">{error || "Venue not found"}</h1>
                    <Link href="/venues">
                        <Button variant="outline">
                            <ArrowLeft className="h-4 w-4 mr-2" />
                            Back to Venues
                        </Button>
                    </Link>
                </div>
            </div>
        )
    }

    return (
        <div className="container py-10 space-y-8">
            {/* Header */}
            <div className="flex items-start gap-4">
                <Link href="/venues">
                    <Button variant="ghost" size="icon">
                        <ArrowLeft className="h-4 w-4" />
                    </Button>
                </Link>
                <div className="flex-1">
                    <h1 className="text-3xl font-bold tracking-tight">{venue.name}</h1>
                    <p className="text-muted-foreground flex items-center gap-2 mt-1">
                        <MapPin className="h-4 w-4" />
                        {venue.city}{venue.state ? `, ${venue.state}` : ""}, {venue.country}
                    </p>
                </div>
                <div className="text-right">
                    <div className="text-3xl font-bold text-primary">{shows.length}</div>
                    <div className="text-sm text-muted-foreground">
                        {shows.length === 1 ? "show" : "shows"}
                    </div>
                </div>
            </div>

            <div className="grid gap-6 lg:grid-cols-[2fr_1fr]">
                {/* Shows List */}
                <Card>
                    <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                            <Calendar className="h-5 w-5" />
                            Shows at {venue.name}
                        </CardTitle>
                    </CardHeader>
                    <CardContent>
                        {shows.length > 0 ? (
                            <div className="space-y-2">
                                {shows.map((show) => (
                                    <Link key={show.id} href={show.vertical ? `/${show.vertical.slug}/shows/${show.slug}` : `/shows/${show.slug}`} className="block group">
                                        <div className="flex items-center justify-between p-3 rounded-md hover:bg-muted/50 transition-colors border">
                                            <div className="flex items-center gap-3">
                                                <Calendar className="h-4 w-4 text-muted-foreground" />
                                                <span className="font-medium group-hover:text-primary transition-colors">
                                                    {new Date(show.date).toLocaleDateString("en-US", {
                                                        weekday: "short",
                                                        year: "numeric",
                                                        month: "short",
                                                        day: "numeric"
                                                    })}
                                                </span>
                                                {show.vertical && (
                                                    <span className="inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold bg-primary text-primary-foreground">
                                                        {show.vertical.name}
                                                    </span>
                                                )}
                                            </div>
                                            <div className="flex items-center gap-4">
                                                {show.tour && (
                                                    <span className="text-xs text-muted-foreground bg-muted px-2 py-1 rounded">
                                                        {show.tour.name}
                                                    </span>
                                                )}
                                                {show.performances && show.performances.length > 0 && (
                                                    <span className="text-xs text-muted-foreground flex items-center gap-1">
                                                        <Music className="h-3 w-3" />
                                                        {show.performances.length}
                                                    </span>
                                                )}
                                            </div>
                                        </div>
                                    </Link>
                                ))}
                            </div>
                        ) : (
                            <p className="text-muted-foreground text-sm text-center py-8">
                                No shows recorded at this venue yet.
                            </p>
                        )}
                    </CardContent>
                </Card>

                {/* Sidebar */}
                <div className="space-y-6">
                    {/* Venue Details */}
                    <Card>
                        <CardHeader>
                            <CardTitle>Venue Details</CardTitle>
                        </CardHeader>
                        <CardContent className="space-y-3">
                            <div className="flex justify-between text-sm">
                                <span className="text-muted-foreground">Location</span>
                                <span className="font-medium text-right">
                                    {venue.city}{venue.state ? `, ${venue.state}` : ""}
                                    <br />
                                    <span className="text-muted-foreground">{venue.country}</span>
                                </span>
                            </div>
                            {venue.capacity && (
                                <div className="flex justify-between text-sm">
                                    <span className="text-muted-foreground">Capacity</span>
                                    <span className="font-medium">{venue.capacity.toLocaleString()}</span>
                                </div>
                            )}
                            <div className="flex justify-between text-sm">
                                <span className="text-muted-foreground">Total Shows</span>
                                <span className="font-medium">{shows.length}</span>
                            </div>
                            {shows.length > 0 && (
                                <>
                                    <div className="flex justify-between text-sm">
                                        <span className="text-muted-foreground">First Show</span>
                                        <span className="font-medium">
                                            {new Date(shows[shows.length - 1].date).toLocaleDateString()}
                                        </span>
                                    </div>
                                    <div className="flex justify-between text-sm">
                                        <span className="text-muted-foreground">Last Show</span>
                                        <span className="font-medium">
                                            {new Date(shows[0].date).toLocaleDateString()}
                                        </span>
                                    </div>
                                </>
                            )}
                            {venue.notes && (
                                <div className="pt-3 border-t mt-3">
                                    <p className="text-sm text-muted-foreground italic">{venue.notes}</p>
                                </div>
                            )}
                        </CardContent>
                    </Card>

                    {/* Quick Stats */}
                    {shows.length > 0 && (
                        <Card>
                            <CardHeader>
                                <CardTitle className="text-sm">Quick Stats</CardTitle>
                            </CardHeader>
                            <CardContent>
                                <div className="grid grid-cols-2 gap-4 text-center">
                                    <div>
                                        <div className="text-2xl font-bold text-primary">{shows.length}</div>
                                        <div className="text-xs text-muted-foreground">Shows</div>
                                    </div>
                                    <div>
                                        <div className="text-2xl font-bold">
                                            {shows.reduce((acc, s) => acc + (s.performances?.length || 0), 0)}
                                        </div>
                                        <div className="text-xs text-muted-foreground">Performances</div>
                                    </div>
                                </div>
                            </CardContent>
                        </Card>
                    )}
                </div>
            </div>
        </div>
    )
}
