"use client"

import type React from "react"

import { useState, useEffect } from "react"
import { Download, Check, Loader2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { offlineStorage, downloadTrackForOffline } from "@/lib/offline-storage"
import { usePlayer } from "@/components/player-provider"
import { useUser } from "@/components/user-provider"
import { useAuth } from "@/components/auth-provider"
import { toast } from "sonner"

interface DownloadButtonProps {
  track: {
    id: string
    title: string
    artist: string
    album?: string
    cover_url?: string
    duration_ms: number
    audio_url: string
  }
  variant?: "icon" | "button"
  size?: "sm" | "default"
}

export function DownloadButton({ track, variant = "icon", size = "default" }: DownloadButtonProps) {
  const { toggleDownload } = usePlayer()
  const { settings } = useUser()
  const { user } = useAuth()
  const [isDownloaded, setIsDownloaded] = useState(false)
  const [isDownloading, setIsDownloading] = useState(false)
  const [progress, setProgress] = useState(0)

  useEffect(() => {
    async function checkDownloadStatus() {
      if (!offlineStorage || !user?.id) return
      try {
        await offlineStorage.initForUser(user.id)
        const downloaded = await offlineStorage.isTrackDownloaded(track.id)
        setIsDownloaded(downloaded)
      } catch (error) {
        console.error("[v0] Failed to check download status:", error)
      }
    }
    checkDownloadStatus()
  }, [track.id, user?.id])

  const handleDownload = async (e: React.MouseEvent) => {
    e.preventDefault()
    e.stopPropagation()

    if (isDownloading || !offlineStorage) return

    if (!user?.id) {
      toast.error("Connectez-vous pour telecharger des titres")
      return
    }

    // Ensure offline storage is initialized
    await offlineStorage.initForUser(user.id)

    if (isDownloaded) {
      // Remove download
      try {
        await offlineStorage.deleteTrack(track.id)
        setIsDownloaded(false)
        toggleDownload(track.id)
        toast.success(`"${track.title}" a ete supprime de vos telechargements`)
      } catch (error) {
        console.error("Failed to remove download:", error)
        toast.error("Impossible de supprimer le telechargement")
      }
      return
    }

    setIsDownloading(true)
    setProgress(0)

    toast.info(`"${track.title}" est en cours de telechargement...`)

    console.log("[v0] Starting in-app download for:", track.title, "user:", user.id)
    console.log("[v0] Storage initialized for:", offlineStorage.getCurrentUserId())
    console.log("[v0] Track audio_url:", track.audio_url)

    try {
      const success = await downloadTrackForOffline(track, (p) => setProgress(p), settings.downloadQuality)
      console.log("[v0] downloadTrackForOffline returned:", success)
      if (success) {
        setIsDownloaded(true)
        toggleDownload(track.id)
        toast.success(`"${track.title}" est maintenant disponible hors ligne`)
        console.log("[v0] Download completed successfully:", track.title)
        
        // Verify the track was saved
        const savedTrack = await offlineStorage.getTrack(track.id)
        console.log("[v0] Verification - Track saved:", savedTrack ? "YES" : "NO", savedTrack)
      } else {
        throw new Error("Download failed - downloadTrackForOffline returned false")
      }
    } catch (error) {
      console.error("[v0] Download failed:", error)
      toast.error("Impossible de telecharger le morceau. Verifiez votre connexion.")
    } finally {
      setIsDownloading(false)
      setProgress(0)
    }
  }

  if (variant === "icon") {
    return (
      <button
        onClick={handleDownload}
        disabled={isDownloading}
        className={`p-2 transition-colors ${
          isDownloaded ? "text-primary" : "text-muted-foreground hover:text-foreground"
        } ${isDownloading ? "cursor-wait" : "cursor-pointer"}`}
        aria-label={isDownloaded ? "Supprimer le telechargement" : "Telecharger"}
        title={isDownloaded ? "Supprimer le telechargement" : "Telecharger pour ecouter hors ligne"}
      >
        {isDownloading ? (
          <div className="relative">
            <Loader2 className="h-5 w-5 animate-spin" />
            {progress > 0 && (
              <span className="absolute -bottom-1 -right-1 text-[8px] font-bold bg-primary text-primary-foreground rounded-full w-4 h-4 flex items-center justify-center">
                {Math.round(progress)}
              </span>
            )}
          </div>
        ) : isDownloaded ? (
          <Check className="h-5 w-5" />
        ) : (
          <Download className="h-5 w-5" />
        )}
      </button>
    )
  }

  return (
    <Button
      onClick={handleDownload}
      disabled={isDownloading}
      variant={isDownloaded ? "secondary" : "default"}
      size={size}
      className="gap-2"
    >
      {isDownloading ? (
        <>
          <Loader2 className="h-4 w-4 animate-spin" />
          {progress > 0 ? `${Math.round(progress)}%` : "Téléchargement..."}
        </>
      ) : isDownloaded ? (
        <>
          <Check className="h-4 w-4" />
          Téléchargé
        </>
      ) : (
        <>
          <Download className="h-4 w-4" />
          Télécharger
        </>
      )}
    </Button>
  )
}
