"use client"

import { useState, useEffect } from "react"
import { X, Heart, ListPlus, Share2, Radio, User, Disc, Download, Ban, Clock, Loader2 } from "lucide-react"
import { usePlayer } from "@/components/player-provider"
import { AddToPlaylistModal } from "@/components/add-to-playlist-modal"
import { ShareModal } from "@/components/share-modal"
import type { Track } from "@/lib/music-data"
import Image from "next/image"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { useUser } from "@/components/user-provider"
import { useAuth } from "@/components/auth-provider"
import { toast } from "sonner"
import { offlineStorage, downloadTrackForOffline } from "@/lib/offline-storage"

interface TrackOptionsModalProps {
  track: Track
  isOpen: boolean
  onClose: () => void
}

export function TrackOptionsModal({ track, isOpen, onClose }: TrackOptionsModalProps) {
  const { toggleLike, isLiked, addToQueue } = usePlayer()
  const { settings } = useUser()
  const { user } = useAuth()
  const [showPlaylistModal, setShowPlaylistModal] = useState(false)
  const [showShareModal, setShowShareModal] = useState(false)
  const [isDownloading, setIsDownloading] = useState(false)
  const [isDownloaded, setIsDownloaded] = useState(false)
  const router = useRouter()

  useEffect(() => {
    async function checkDownloadStatus() {
      if (!isOpen || !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()
  }, [isOpen, track.id, user?.id])

  const handleDownload = async () => {
    if (isDownloading) return

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

    try {
      if (isDownloaded) {
        // Remove from offline storage
        if (!offlineStorage) {
          toast.error("Stockage hors ligne non disponible")
          return
        }

        await offlineStorage.deleteTrack(track.id)
        setIsDownloaded(false)
        toast.success("Telechargement supprime")
        onClose()
      } else {
        // Download to IndexedDB
        if (!offlineStorage) {
          toast.error("Stockage hors ligne non disponible")
          return
        }

        setIsDownloading(true)
        toast.info("Telechargement en cours...")
        
        await offlineStorage.initForUser(user.id)

        const success = await downloadTrackForOffline(
          {
            id: track.id,
            title: track.title,
            artist: track.artist,
            album: track.album,
            cover_url: track.image,
            duration_ms: track.duration || 0,
            audio_url: track.audioUrl || `/api/stream/${track.id}`,
          },
          (progress) => {
            console.log("[v0] Download progress:", Math.round(progress), "%")
          },
          settings.downloadQuality || "normal",
        )

        setIsDownloading(false)

        if (success) {
          setIsDownloaded(true)
          toast.success("Téléchargement terminé")
          console.log("[v0] Download completed successfully")
          onClose()
        } else {
          toast.error("Erreur lors du téléchargement")
          console.error("[v0] Download failed")
        }
      }
    } catch (error) {
      console.error("[v0] Download error:", error)
      toast.error("Erreur lors du téléchargement")
      setIsDownloading(false)
    }
  }

  if (!isOpen) return null

  const options = [
    {
      icon: Heart,
      label: isLiked(track.id) ? "Retirer des favoris" : "Ajouter aux favoris",
      action: () => {
        toggleLike(track.id)
        onClose()
      },
      active: isLiked(track.id),
    },
    {
      icon: ListPlus,
      label: "Ajouter à une playlist",
      action: () => setShowPlaylistModal(true),
    },
    {
      icon: Clock,
      label: "Ajouter à la file d'attente",
      action: () => {
        addToQueue(track)
        onClose()
      },
    },
    {
      icon: Share2,
      label: "Partager",
      action: () => setShowShareModal(true),
    },
    {
      icon: Radio,
      label: "Accéder à la radio du titre",
      action: () => {
        router.push(`/radio/${track.id}`)
        onClose()
      },
    },
    {
      icon: User,
      label: "Voir l'artiste",
      href: `/artist/${track.artistId || "1"}`,
    },
    {
      icon: Disc,
      label: "Voir l'album",
      href: `/album/${track.albumId || "1"}`,
    },
    {
      icon: isDownloading ? Loader2 : Download,
      label: isDownloaded ? "Supprimer le téléchargement" : "Télécharger",
      action: handleDownload,
      active: isDownloaded,
      loading: isDownloading,
    },
    {
      icon: Ban,
      label: "Masquer ce titre",
      action: onClose,
      destructive: true,
    },
  ]

  return (
    <>
      <div className="fixed inset-0 z-50 flex items-end justify-center bg-black/60 backdrop-blur-sm" onClick={onClose}>
        <div className="w-full max-w-md rounded-t-3xl bg-background p-6 pb-8" onClick={(e) => e.stopPropagation()}>
          {/* Header with track info */}
          <div className="mb-6 flex items-center gap-4">
            <div className="relative h-16 w-16 overflow-hidden rounded-lg">
              <Image src={track.image || "/placeholder.svg"} alt={track.title} fill className="object-cover" />
            </div>
            <div className="flex-1 min-w-0">
              <p className="truncate font-semibold text-foreground">{track.title}</p>
              <p className="truncate text-sm text-muted-foreground">{track.artist}</p>
            </div>
            <button onClick={onClose} className="text-muted-foreground hover:text-foreground">
              <X className="h-6 w-6" />
            </button>
          </div>

          {/* Options */}
          <div className="max-h-80 space-y-1 overflow-y-auto">
            {options.map((option, index) => {
              const content = (
                <>
                  <option.icon
                    className={`h-5 w-5 ${
                      option.loading
                        ? "animate-spin"
                        : option.destructive
                          ? "text-destructive"
                          : option.active
                            ? "text-primary fill-primary"
                            : "text-muted-foreground"
                    }`}
                  />
                  <span className={option.destructive ? "text-destructive" : "text-foreground"}>{option.label}</span>
                </>
              )

              if (option.href) {
                return (
                  <Link
                    key={index}
                    href={option.href}
                    onClick={onClose}
                    className="flex w-full items-center gap-4 rounded-lg p-3 transition-colors hover:bg-secondary"
                  >
                    {content}
                  </Link>
                )
              }

              return (
                <button
                  key={index}
                  onClick={option.action}
                  disabled={option.loading}
                  className="flex w-full items-center gap-4 rounded-lg p-3 transition-colors hover:bg-secondary disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {content}
                </button>
              )
            })}
          </div>
        </div>
      </div>

      <AddToPlaylistModal track={track} isOpen={showPlaylistModal} onClose={() => setShowPlaylistModal(false)} />
      <ShareModal
        isOpen={showShareModal}
        onClose={() => setShowShareModal(false)}
        item={{ type: "track", title: track.title, subtitle: track.artist, image: track.image }}
      />
    </>
  )
}
