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

interface Song {
    id: number
    title: string
    slug?: string
    original_artist?: string
}

export default function SongsPage() {
    const [songs, setSongs] = useState<Song[]>([])
    const [loading, setLoading] = useState(true)

    useEffect(() => {
        fetch(`${getApiUrl()}/songs/?limit=1000`)
            .then(res => res.json())
            .then(data => {
                if (!Array.isArray(data)) {
                    console.error("API Error: Expected array but got:", data)
                    return
                }
                // Sort alphabetically
                const sorted = data.sort((a: Song, b: Song) => a.title.localeCompare(b.title))
                setSongs(sorted)
            })
            .catch(console.error)
            .finally(() => setLoading(false))
    }, [])

    if (loading) return <div className="container py-10">Loading songs...</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">Songs</h1>
                <p className="text-muted-foreground">
                    Every song played, from originals to rare covers.
                </p>
            </div>

            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
                {songs.map((song) => (
                    <Link key={song.slug} href={`/songs/${song.slug}`}>
                        <Card className="h-full hover:bg-accent/50 transition-colors">
                            <CardHeader>
                                <CardTitle className="flex items-center gap-2">
                                    <Music className="h-5 w-5 text-purple-500" />
                                    {song.title}
                                </CardTitle>
                            </CardHeader>
                            <CardContent>
                                {song.original_artist && (
                                    <p className="text-sm text-muted-foreground">
                                        Original by {song.original_artist}
                                    </p>
                                )}
                            </CardContent>
                        </Card>
                    </Link>
                ))}
            </div>
        </div>
    )
}
