"use client"

import Image from "next/image"
import Link from "next/link"
import { ChevronLeft, Play, Loader2 } from "lucide-react"
import { BottomNav } from "@/components/bottom-nav"
import useSWR from "swr"

const fetcher = (url: string) => fetch(url).then((res) => res.json())

function formatRelativeDate(dateString: string) {
  const date = new Date(dateString)
  const now = new Date()
  const diffTime = now.getTime() - date.getTime()
  const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))

  if (diffDays === 0) return "Aujourd'hui"
  if (diffDays === 1) return "Hier"
  if (diffDays < 7) return `Il y a ${diffDays} jours`
  if (diffDays < 30) return `Il y a ${Math.floor(diffDays / 7)} semaines`
  return `Il y a ${Math.floor(diffDays / 30)} mois`
}

export default function NewReleasesPage() {
  const { data: albumsData, isLoading: albumsLoading } = useSWR("/api/albums?sort=newest&limit=20", fetcher, {
    dedupingInterval: 60000,
  })
  const { data: tracksData, isLoading: tracksLoading } = useSWR("/api/tracks?sort=newest&limit=20", fetcher, {
    dedupingInterval: 60000,
  })

  const isLoading = albumsLoading || tracksLoading

  // Combine and sort by release date
  const newReleases = [
    ...(albumsData?.data || []).map((album: any) => ({
      id: album.id,
      title: album.title,
      artist: album.artist_name || "Artiste inconnu",
      image: album.cover_url,
      date: album.release_date || album.created_at,
      type: "album",
    })),
    ...(tracksData?.data || []).map((track: any) => ({
      id: track.id,
      title: track.title,
      artist: track.artist_name || "Artiste inconnu",
      image: track.cover_url,
      date: track.created_at,
      type: "track",
    })),
  ]
    .sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
    .slice(0, 20)

  return (
    <div className="min-h-screen bg-background pb-24">
      <div className="mx-auto max-w-md px-4 py-6">
        {/* Header */}
        <div className="mb-6 flex items-center gap-4">
          <Link href="/" className="text-foreground hover:text-primary">
            <ChevronLeft className="h-6 w-6" />
          </Link>
          <h1 className="text-xl font-bold text-foreground">Nouveautés</h1>
        </div>

        {isLoading ? (
          <div className="flex items-center justify-center py-12">
            <Loader2 className="h-8 w-8 animate-spin text-primary" />
          </div>
        ) : newReleases.length === 0 ? (
          <div className="text-center py-12">
            <p className="text-muted-foreground">Aucune nouveauté disponible</p>
          </div>
        ) : (
          /* Albums Grid */
          <div className="grid grid-cols-2 gap-4">
            {newReleases.map((item) => (
              <Link
                key={`${item.type}-${item.id}`}
                href={item.type === "album" ? `/album/${item.id}` : `/track/${item.id}`}
                className="group"
              >
                <div className="relative mb-2 aspect-square overflow-hidden rounded-xl">
                  <Image
                    src={item.image || "/placeholder.svg?height=200&width=200&query=music album"}
                    alt={item.title}
                    fill
                    className="object-cover transition-transform group-hover:scale-105"
                  />
                  <div className="absolute inset-0 flex items-center justify-center bg-black/0 opacity-0 transition-all group-hover:bg-black/40 group-hover:opacity-100">
                    <div className="flex h-12 w-12 items-center justify-center rounded-full bg-primary text-primary-foreground">
                      <Play className="h-5 w-5 ml-0.5" />
                    </div>
                  </div>
                </div>
                <p className="truncate font-medium text-foreground">{item.title}</p>
                <p className="truncate text-sm text-muted-foreground">{item.artist}</p>
                <p className="text-xs text-muted-foreground/70">{formatRelativeDate(item.date)}</p>
              </Link>
            ))}
          </div>
        )}
      </div>

      <BottomNav />
    </div>
  )
}
