"use client"

import { useState, useEffect } from "react"
import Image from "next/image"
import Link from "next/link"
import { ChevronLeft, Play, Trash2, Download, WifiOff, Check, Loader2, Music } from "lucide-react"
import { BottomNav } from "@/components/bottom-nav"
import { Button } from "@/components/ui/button"
import { StorageBar } from "@/components/storage-bar"
import { usePlayer } from "@/components/player-provider"
import { useAuth } from "@/components/auth-provider"
import { offlineStorage, getOfflineAudioUrl } from "@/lib/offline-storage"
import { toast } from "sonner"

export default function DownloadsPage() {
  const { user } = useAuth()
  const { playTrack, playAlbum, currentTrack, isPlaying, togglePlay, isOfflineMode } = usePlayer()
  const [offlineTracks, setOfflineTracks] = useState<any[]>([])
  const [storageUsed, setStorageUsed] = useState(0)
  const [isLoading, setIsLoading] = useState(true)
  const [imageErrors, setImageErrors] = useState<Set<string>>(new Set())
  const [storageError, setStorageError] = useState<string | null>(null)

  useEffect(() => {
    async function loadOfflineTracks() {
      console.log("[v0] Downloads page - Loading offline tracks for user:", user?.id)

      if (!offlineStorage) {
        console.error("[v0] Downloads page - Offline storage not available")
        setStorageError("Stockage hors ligne non disponible. Verifiez les parametres de votre navigateur.")
        setIsLoading(false)
        return
      }

      if (!user?.id) {
        console.log("[v0] Downloads page - No user logged in")
        setIsLoading(false)
        return
      }

      try {
        await offlineStorage.initForUser(user.id)
        console.log("[v0] Downloads page - Offline storage initialized for user:", user.id)
        console.log("[v0] Downloads page - Current storage user:", offlineStorage.getCurrentUserId())

        const tracks = await offlineStorage.getAllTracks()
        console.log("[v0] Downloads page - Loaded offline tracks:", tracks.length, "tracks:", tracks.map(t => ({id: t.id, title: t.title})))

        // Verify each track has audio blob
        const validTracks = []
        for (const track of tracks) {
          const hasAudio = await offlineStorage.getAudioBlob(track.id)
          if (hasAudio) {
            validTracks.push(track)
          } else {
            console.warn("[v0] Downloads page - Track has no audio blob:", track.id)
          }
        }

        setOfflineTracks(validTracks)

        const size = await offlineStorage.getStorageUsed()
        console.log("[v0] Downloads page - Storage used:", (size / (1024 * 1024)).toFixed(2), "MB")
        setStorageUsed(size / (1024 * 1024)) // Convert to MB
        setStorageError(null)
      } catch (error) {
        console.error("[v0] Downloads page - Failed to load offline tracks:", error)
        setStorageError("Erreur de chargement des telechargements")
      } finally {
        setIsLoading(false)
      }
    }

    loadOfflineTracks()

    // Reload tracks every 5 seconds to catch new downloads
    const interval = setInterval(loadOfflineTracks, 5000)
    return () => clearInterval(interval)
  }, [user?.id])

  const formatDuration = (ms: number) => {
    const minutes = Math.floor(ms / 60000)
    const seconds = Math.floor((ms % 60000) / 1000)
    return `${minutes}:${seconds.toString().padStart(2, "0")}`
  }

  const handlePlayAll = async () => {
    if (offlineTracks.length > 0) {
      console.log("[v0] Downloads page - Playing all tracks:", offlineTracks.length)
      const tracksToPlay = await Promise.all(
        offlineTracks.map(async (song: any) => {
          const offlineUrl = await getOfflineAudioUrl(song.id)
          return {
            id: song.id,
            title: song.title,
            artist: song.artist || song.artist_name || "Unknown",
            image: song.cover_url || "/abstract-music-album.png",
            cover_url: song.cover_url,
            duration: (song.duration_ms || 0) / 1000,
            audioUrl: offlineUrl || song.audio_url,
            isOffline: !!offlineUrl,
          }
        }),
      )
      playAlbum(tracksToPlay, 0)
    }
  }

  const handlePlayTrack = async (song: any) => {
    console.log("[v0] Downloads page - Playing track:", song.title, "ID:", song.id)

    const offlineUrl = await getOfflineAudioUrl(song.id)
    console.log("[v0] Downloads page - Offline URL available:", !!offlineUrl)

    if (!offlineUrl) {
      toast.error("Impossible de lire ce titre hors ligne")
      return
    }

    const track = {
      id: song.id,
      title: song.title,
      artist: song.artist || song.artist_name || "Unknown",
      image: song.cover_url || "/abstract-music-album.png",
      cover_url: song.cover_url,
      duration: (song.duration_ms || 0) / 1000,
      audioUrl: offlineUrl,
      isOffline: true,
    }

    if (currentTrack?.id === song.id) {
      togglePlay()
    } else {
      playTrack(track)
    }
  }

  const handleRemoveDownload = async (trackId: string) => {
    console.log("[v0] Downloads page - Removing track:", trackId)
    try {
      if (offlineStorage) {
        await offlineStorage.deleteTrack(trackId)
        setOfflineTracks((prev) => prev.filter((t) => t.id !== trackId))
        const size = await offlineStorage.getStorageUsed()
        setStorageUsed(size / (1024 * 1024))

        toast.success("Le titre a ete supprime des telechargements")
      }
    } catch (error) {
      console.error("[v0] Downloads page - Failed to remove download:", error)
      toast.error("Impossible de supprimer le telechargement")
    }
  }

  const handleImageError = (id: string) => {
    setImageErrors((prev) => new Set(prev).add(id))
  }

  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 justify-between">
          <div className="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">Telechargements</h1>
          </div>
          <div className={`flex items-center gap-2 ${isOfflineMode ? "text-destructive" : "text-muted-foreground"}`}>
            <WifiOff className="h-4 w-4" />
            <span className="text-sm">{isOfflineMode ? "Hors ligne" : ""}</span>
          </div>
        </div>

        {storageError && (
          <div className="mb-4 rounded-lg bg-destructive/10 p-4 text-sm text-destructive">{storageError}</div>
        )}

        {/* Storage */}
        <div className="mb-6">
          <StorageBar used={storageUsed / 1000} total={64} />
          <p className="mt-2 text-xs text-muted-foreground text-center">
            {offlineTracks.length} titres telecharges ({storageUsed.toFixed(1)} MB)
          </p>
        </div>

        {/* Downloaded Songs */}
        <section className="mb-8">
          <h2 className="mb-4 text-lg font-semibold text-foreground">Titres telecharges</h2>
          {isLoading ? (
            <div className="flex items-center justify-center py-12">
              <Loader2 className="h-8 w-8 animate-spin text-primary" />
            </div>
          ) : offlineTracks.length === 0 ? (
            <div className="py-12 text-center">
              <Download className="mx-auto h-12 w-12 text-muted-foreground mb-4" />
              <p className="text-muted-foreground">Aucun telechargement</p>
              <p className="text-sm text-muted-foreground mt-1">Telechargez des titres pour les ecouter hors ligne</p>
              {storageError && (
                <p className="text-xs text-destructive mt-2">
                  Verifiez que le stockage local est autorise dans votre navigateur
                </p>
              )}
              {isOfflineMode && (
                <div className="mt-4 p-3 bg-orange-500/10 rounded-lg">
                  <p className="text-sm text-orange-600 dark:text-orange-400">
                    Vous etes hors ligne. Connectez-vous pour telecharger des titres.
                  </p>
                </div>
              )}
            </div>
          ) : (
            <div className="space-y-1">
              {offlineTracks.map((song: any) => {
                const isCurrentTrack = currentTrack?.id === song.id
                const hasImageError = imageErrors.has(song.id)
                return (
                  <div
                    key={song.id}
                    className={`flex items-center gap-3 rounded-lg p-2 transition-colors hover:bg-secondary ${isCurrentTrack ? "bg-secondary/50" : ""}`}
                  >
                    <button
                      onClick={() => handlePlayTrack(song)}
                      className="relative h-12 w-12 overflow-hidden rounded flex-shrink-0 bg-secondary"
                    >
                      {!hasImageError && song.cover_url ? (
                        <Image
                          src={song.cover_url || "/placeholder.svg"}
                          alt={song.title}
                          fill
                          className="object-cover"
                          onError={() => handleImageError(song.id)}
                        />
                      ) : (
                        <div className="flex h-full w-full items-center justify-center bg-gradient-to-br from-primary/20 to-primary/5">
                          <Music className="h-5 w-5 text-muted-foreground" />
                        </div>
                      )}
                      <div className="absolute bottom-0.5 right-0.5 rounded-full bg-green-500 p-0.5">
                        <Check className="h-2 w-2 text-white" />
                      </div>
                      {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>
                      )}
                    </button>
                    <div className="flex-1 min-w-0">
                      <h3 className={`font-medium truncate ${isCurrentTrack ? "text-primary" : "text-foreground"}`}>
                        {song.title}
                      </h3>
                      <p className="text-sm text-muted-foreground truncate">
                        {song.artist || song.artist_name || "Unknown"}
                      </p>
                    </div>
                    <span className="text-xs text-muted-foreground">{formatDuration(song.duration_ms || 0)}</span>
                    <button
                      onClick={() => handleRemoveDownload(song.id)}
                      className="p-2 text-muted-foreground hover:text-destructive"
                    >
                      <Trash2 className="h-4 w-4" />
                    </button>
                  </div>
                )
              })}
            </div>
          )}
        </section>

        {offlineTracks.length > 0 && (
          <div className="fixed bottom-24 left-1/2 -translate-x-1/2">
            <Button className="gap-2 rounded-full px-8" onClick={handlePlayAll}>
              <Play className="h-4 w-4 fill-current" />
              Lecture hors ligne
            </Button>
          </div>
        )}
      </div>

      <BottomNav />
    </div>
  )
}
