"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 { Map } from "lucide-react"

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

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

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

    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>

            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
                {tours.map((tour) => (
                    <Link key={tour.id} href={`/tours/${tour.id}`}>
                        <Card className="h-full hover:bg-accent/50 transition-colors">
                            <CardHeader>
                                <CardTitle className="flex items-center gap-2">
                                    <Map className="h-5 w-5 text-orange-500" />
                                    {tour.name}
                                </CardTitle>
                            </CardHeader>
                            <CardContent>
                                <p className="text-sm text-muted-foreground">
                                    {new Date(tour.start_date).toLocaleDateString()} - {new Date(tour.end_date).toLocaleDateString()}
                                </p>
                            </CardContent>
                        </Card>
                    </Link>
                ))}
            </div>
        </div>
    )
}
