"use client"

import { useEffect, useState } from "react"
import { getApiUrl } from "@/lib/api-config"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import Link from "next/link"
import { Map, Calendar } from "lucide-react"

interface Tour {
    id: number
    name: string
    slug: string
    start_date: string
    end_date: string
    show_count: number
}

export default function ToursPage() {
    const [tours, setTours] = useState<Tour[]>([])
    const [loading, setLoading] = useState(true)

    useEffect(() => {
        fetch(`${getApiUrl()}/tours/?limit=200`)
            .then(res => res.json())
            .then(data => {
                // Sort by start date descending
                const sorted = data.sort((a: Tour, b: Tour) =>
                    new Date(b.start_date).getTime() - new Date(a.start_date).getTime()
                )
                setTours(sorted)
            })
            .catch(console.error)
            .finally(() => setLoading(false))
    }, [])

    // Group tours by year
    const toursByYear = tours.reduce((acc, tour) => {
        const year = new Date(tour.start_date).getFullYear()
        if (!acc[year]) acc[year] = []
        acc[year].push(tour)
        return acc
    }, {} as Record<number, Tour[]>)

    const years = Object.keys(toursByYear).map(Number).sort((a, b) => b - a)

    if (loading) return <div className="container py-10">Loading tours...</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">Tours</h1>
                <p className="text-muted-foreground">
                    Follow the band across the country, tour by tour.
                </p>
            </div>

            {years.map(year => (
                <div key={year} className="space-y-4">
                    <h2 className="text-xl font-semibold text-muted-foreground border-b pb-2">{year}</h2>
                    <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
                        {toursByYear[year].map((tour) => (
                            <Link key={tour.id} href={`/tours/${tour.slug || tour.id}`}>
                                <Card className="h-full hover:bg-accent/50 transition-colors">
                                    <CardHeader className="pb-2">
                                        <CardTitle className="flex items-center justify-between">
                                            <span className="flex items-center gap-2">
                                                <Map className="h-5 w-5 text-orange-500" />
                                                {tour.name}
                                            </span>
                                            <Badge variant="secondary" className="ml-2">
                                                {tour.show_count} shows
                                            </Badge>
                                        </CardTitle>
                                    </CardHeader>
                                    <CardContent>
                                        <p className="text-sm text-muted-foreground flex items-center gap-2">
                                            <Calendar className="h-4 w-4" />
                                            {new Date(tour.start_date).toLocaleDateString("en-US", { month: "short", day: "numeric" })}
                                            {" - "}
                                            {new Date(tour.end_date).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}
                                        </p>
                                    </CardContent>
                                </Card>
                            </Link>
                        ))}
                    </div>
                </div>
            ))}
        </div>
    )
}

