"use client"

import { useState, useEffect } from "react"
import Image from "next/image"
import Link from "next/link"
import { ChevronLeft, Clock, Play, WifiOff } from "lucide-react"
import { BottomNav } from "@/components/bottom-nav"
import { usePlayer } from "@/components/player-provider"
import { useAuth } from "@/components/auth-provider"
import { formatDuration } from "@/lib/music-data"

export default function RecentlyPlayedPage() {
  const { playTrack, currentTrack, isPlaying, togglePlay, isOfflineMode } = usePlayer()
  const { user } = useAuth()
  const [history, setHistory] = useState<any[]>([])
  const [isLoading, setIsLoading] = useState(true)

  useEffect(() => {
    async function fetchHistory() {
      if (!user?.id) {
        setIsLoading(false)
        return
      }

      try {
        console.log("[v0] Fetching listening history for user:", user.id)
        const response = await fetch(`/api/history?userId=${user.id}&limit=50`)

        if (!response.ok) {
          throw new Error(`Failed to fetch history: ${response.status}`)
        }

        const result = await response.json()
        console.log("[v0] Listening history loaded:", result.data?.length || 0, "tracks")

        if (result.data && Array.isArray(result.data)) {
          // Transform API data to Track format
          const tracks = result.data.map((item: any) => ({
            id: item.track_id,
            title: item.title,
            artist: item.artist_name || "Unknown Artist",
            image: item.cover_url || "/placeholder.svg",
            duration: item.duration || 0,
            audioUrl: item.audio_url,
            playedAt: item.played_at,
          }))
          setHistory(tracks)
        }
      } catch (error) {
        console.error("[v0] Error fetching listening history:", error)
      } finally {
        setIsLoading(false)
      }
    }

    fetchHistory()
  }, [user?.id])

  // Format relative time from timestamp
  const getRelativeTime = (playedAt: string) => {
    const now = new Date()
    const played = new Date(playedAt)
    const diffMinutes = Math.floor((now.getTime() - played.getTime()) / (1000 * 60))

    if (diffMinutes < 1) return "À l'instant"
    if (diffMinutes < 5) return "Il y a quelques minutes"
    if (diffMinutes < 60) return `Il y a ${diffMinutes} min`

    const diffHours = Math.floor(diffMinutes / 60)
    if (diffHours < 24) return `Il y a ${diffHours}h`

    const diffDays = Math.floor(diffHours / 24)
    if (diffDays === 1) return "Hier"
    if (diffDays < 7) return `Il y a ${diffDays} jours`

    return played.toLocaleDateString("fr-FR", { day: "numeric", month: "short" })
  }

  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="/library" className="text-foreground hover:text-primary">
            <ChevronLeft className="h-6 w-6" />
          </Link>
          <h1 className="text-xl font-bold text-foreground">Derniers Écoutés</h1>
          {isOfflineMode && (
            <div className="ml-auto flex items-center gap-1 text-xs text-muted-foreground">
              <WifiOff className="h-4 w-4" />
              <span>Hors ligne</span>
            </div>
          )}
        </div>

        {/* Loading State */}
        {isLoading ? (
          <div className="py-12 text-center">
            <div className="mx-auto h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
            <p className="mt-4 text-muted-foreground">Chargement...</p>
          </div>
        ) : history.length === 0 ? (
          <div className="py-12 text-center">
            <Clock className="mx-auto h-12 w-12 text-muted-foreground mb-4" />
            <p className="text-muted-foreground">Aucun historique</p>
            <Link href="/search" className="mt-2 inline-block text-primary hover:underline">
              Découvrir de la musique
            </Link>
          </div>
        ) : (
          <div className="space-y-1">
            {history.map((track, index) => {
              const isCurrentTrack = currentTrack?.id === track.id
              return (
                <button
                  key={`${track.id}-${index}`}
                  onClick={() => (isCurrentTrack ? togglePlay() : playTrack(track))}
                  className={`flex w-full items-center gap-3 rounded-lg p-2 transition-colors hover:bg-secondary text-left ${isCurrentTrack ? "bg-secondary/50" : ""}`}
                >
                  <div className="relative h-14 w-14 flex-shrink-0 overflow-hidden rounded-lg">
                    <Image src={track.image || "/placeholder.svg"} alt={track.title} fill className="object-cover" />
                    {isCurrentTrack && isPlaying ? (
                      <div className="absolute inset-0 flex items-center justify-center bg-black/50">
                        <div className="flex gap-0.5">
                          <span className="h-3 w-0.5 animate-pulse bg-white" />
                          <span className="h-4 w-0.5 animate-pulse bg-white" style={{ animationDelay: "150ms" }} />
                          <span className="h-2 w-0.5 animate-pulse bg-white" style={{ animationDelay: "300ms" }} />
                        </div>
                      </div>
                    ) : (
                      <div className="absolute inset-0 flex items-center justify-center bg-black/50 opacity-0 hover:opacity-100 transition-opacity">
                        <Play className="h-6 w-6 text-white" />
                      </div>
                    )}
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className={`truncate font-medium ${isCurrentTrack ? "text-primary" : "text-foreground"}`}>
                      {track.title}
                    </p>
                    <p className="truncate text-sm text-muted-foreground">{track.artist}</p>
                  </div>
                  <div className="flex flex-col items-end gap-1">
                    <span className="text-sm text-muted-foreground">{formatDuration(track.duration)}</span>
                    <div className="flex items-center gap-1 text-xs text-muted-foreground">
                      <Clock className="h-3 w-3" />
                      {getRelativeTime(track.playedAt)}
                    </div>
                  </div>
                </button>
              )
            })}
          </div>
        )}
      </div>

      <BottomNav />
    </div>
  )
}
