"use client"

import { useState, useEffect } from "react"
import Image from "next/image"
import Link from "next/link"
import { useParams, useRouter } from "next/navigation"
import { ChevronLeft, Heart, Share2, MoreHorizontal, Play, Plus, Download, Check, Loader2 } from "lucide-react"
import { BottomNav } from "@/components/bottom-nav"
import { Button } from "@/components/ui/button"
import { usePlayer } from "@/components/player-provider"
import { useAuth } from "@/components/auth-provider"
import { AddToPlaylistModal } from "@/components/add-to-playlist-modal"
import { formatDuration } from "@/lib/music-data"
import { useToast } from "@/hooks/use-toast"

interface Track {
  id: string
  title: string
  artist_id: string
  artist_name: string
  artist_avatar: string
  artist_verified: boolean
  album_id: string
  album_title: string
  album_cover: string
  cover_url: string
  duration_ms: number
  total_streams: number
  genre: string
  lyrics: string
  release_date: string
  audio_url: string
}

interface SimilarTrack {
  id: string
  title: string
  artist_name: string
  cover_url: string
  audio_url: string
  duration_ms: number
}

export default function TrackPage() {
  const { id } = useParams<{ id: string }>()
  const router = useRouter()
  const { toast } = useToast()
  const [track, setTrack] = useState<Track | null>(null)
  const [similarTracks, setSimilarTracks] = useState<SimilarTrack[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [liked, setLiked] = useState(false)
  const [likeCount, setLikeCount] = useState(0)
  const [showPlaylistModal, setShowPlaylistModal] = useState(false)
  const [isDownloading, setIsDownloading] = useState(false)
  const [isDownloaded, setIsDownloaded] = useState(false)
  const [isPurchasing, setIsPurchasing] = useState(false)
  const [isPurchased, setIsPurchased] = useState(false)
  const { playTrack } = usePlayer()
  const { user } = useAuth()

  useEffect(() => {
    const fetchTrack = async () => {
      try {
        setIsLoading(true)
        const response = await fetch(`/api/tracks/${id}`)
        if (response.ok) {
          const data = await response.json()
          setTrack(data)

          const likesUrl = user ? `/api/tracks/${id}/likes?userId=${user.id}` : `/api/tracks/${id}/likes`
          const likesRes = await fetch(likesUrl)
          if (likesRes.ok) {
            const likesData = await likesRes.json()
            setLikeCount(likesData.count || 0)
            setLiked(likesData.isLiked || false)
          }

          const similarRes = await fetch(`/api/tracks?limit=5&genre=${data.genre || ""}`)
          if (similarRes.ok) {
            const similarData = await similarRes.json()
            setSimilarTracks((similarData.data || []).filter((t: SimilarTrack) => t.id !== id).slice(0, 3))
          }
        }
      } catch (error) {
        console.error("Error fetching track:", error)
      } finally {
        setIsLoading(false)
      }
    }

    if (id) {
      fetchTrack()
    }
  }, [id, user]) // Add user to dependency array

  const handleLike = async () => {
    if (!user) return

    try {
      const response = await fetch(`/api/tracks/${id}/likes`, {
        method: liked ? "DELETE" : "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ userId: user.id }),
      })

      if (response.ok) {
        setLiked(!liked)
        setLikeCount((prev) => (liked ? prev - 1 : prev + 1))
      }
    } catch (error) {
      console.error("Error toggling like:", error)
    }
  }

  const handlePlay = () => {
    if (track) {
      playTrack({
        id: track.id,
        title: track.title,
        artist: track.artist_name,
        image: track.cover_url || track.album_cover || "/abstract-music-album.png",
        cover_url: track.cover_url,
        album_cover: track.album_cover,
        audioUrl: track.audio_url || "",
        duration: track.duration_ms,
        artistId: track.artist_id,
        albumId: track.album_id,
      })
    }
  }

  const handlePlaySimilar = (similar: SimilarTrack) => {
    playTrack({
      id: similar.id,
      title: similar.title,
      artist: similar.artist_name,
      image: similar.cover_url || "/abstract-music-album.png",
      cover_url: similar.cover_url,
      audioUrl: similar.audio_url || "",
      duration: similar.duration_ms,
    })
  }

  const handleAddToPlaylist = () => {
    if (!user) {
      toast({
        title: "Connectez-vous pour ajouter à une playlist",
        variant: "destructive",
      })
      return
    }
    setShowPlaylistModal(true)
  }

  const handleDownload = async () => {
    if (!user) {
      toast({
        title: "Connectez-vous pour télécharger",
        variant: "destructive",
      })
      return
    }

    if (!track) return

    try {
      setIsDownloading(true)

      const response = await fetch(`/api/tracks/${id}/download`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ userId: user.id }),
      })

      if (response.ok) {
        const data = await response.json()

        if (data.downloadUrl) {
          const link = document.createElement("a")
          link.href = data.downloadUrl
          link.download = `${track.title} - ${track.artist_name}.mp3`
          link.target = "_blank"
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)

          setIsDownloaded(true)
          toast({ title: "Téléchargement démarré" })
        } else {
          toast({ title: "Fichier audio non disponible", variant: "destructive" })
        }
      } else {
        toast({ title: "Erreur lors du téléchargement", variant: "destructive" })
      }
    } catch (error) {
      console.error("Download error:", error)
      toast({ title: "Erreur lors du téléchargement", variant: "destructive" })
    } finally {
      setIsDownloading(false)
    }
  }

  const handleShare = async () => {
    if (!track) return

    const shareUrl = `${window.location.origin}/track/${track.id}`
    const shareData = {
      title: track.title,
      text: `Écoute "${track.title}" par ${track.artist_name} sur notre app!`,
      url: shareUrl,
    }

    try {
      if (navigator.share && navigator.canShare(shareData)) {
        await navigator.share(shareData)
      } else {
        await navigator.clipboard.writeText(shareUrl)
        toast({ title: "Lien copié dans le presse-papiers" })
      }
    } catch (error) {
      if ((error as Error).name !== "AbortError") {
        await navigator.clipboard.writeText(shareUrl)
        toast({ title: "Lien copié dans le presse-papiers" })
      }
    }
  }

  const handlePurchase = async () => {
    if (!user) {
      toast({
        title: "Connectez-vous pour acheter",
        variant: "destructive",
      })
      return
    }

    if (!track) return

    try {
      setIsPurchasing(true)

      const response = await fetch("/api/purchases", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          userId: user.id,
          itemType: "track",
          itemId: track.id,
        }),
      })

      if (response.ok) {
        const data = await response.json()
        setIsPurchased(true)
        toast({
          title: "Achat réussi",
          description: `Vous avez acheté "${track.title}" pour ${data.price} FCFA`,
        })
      } else {
        const error = await response.json()
        toast({
          title: "Erreur d'achat",
          description: error.error || "Une erreur s'est produite",
          variant: "destructive",
        })
      }
    } catch (error) {
      console.error("Purchase error:", error)
      toast({
        title: "Erreur d'achat",
        variant: "destructive",
      })
    } finally {
      setIsPurchasing(false)
    }
  }

  const formatNumber = (num: number) => {
    if (num >= 1000000) return `${(num / 1000000).toFixed(1)}M`
    if (num >= 1000) return `${(num / 1000).toFixed(0)}K`
    return num.toString()
  }

  if (isLoading) {
    return (
      <div className="min-h-screen bg-background pb-24">
        <div className="relative h-80 bg-secondary animate-pulse" />
        <div className="mx-auto max-w-md px-4 py-6 space-y-4">
          <div className="h-8 bg-secondary rounded animate-pulse" />
          <div className="h-4 bg-secondary rounded w-2/3 animate-pulse" />
          <div className="grid grid-cols-3 gap-4">
            {[1, 2, 3].map((i) => (
              <div key={i} className="h-20 bg-secondary rounded-lg animate-pulse" />
            ))}
          </div>
        </div>
        <BottomNav />
      </div>
    )
  }

  if (!track) {
    return (
      <div className="min-h-screen bg-background pb-24 flex items-center justify-center">
        <div className="text-center">
          <h1 className="text-xl font-bold text-foreground mb-2">Piste non trouvée</h1>
          <p className="text-muted-foreground mb-4">Cette piste n'existe pas ou a été supprimée.</p>
          <Link href="/home">
            <Button>Retour à l'accueil</Button>
          </Link>
        </div>
        <BottomNav />
      </div>
    )
  }

  const coverImage = track.cover_url || track.album_cover || "/placeholder.svg"
  const lyricsLines = track.lyrics ? track.lyrics.split("\n") : []

  return (
    <div className="min-h-screen bg-background pb-24">
      <div className="relative h-80">
        <Image src={coverImage || "/placeholder.svg"} alt={track.title} fill className="object-cover" priority />
        <div className="absolute inset-0 bg-gradient-to-t from-background via-background/50 to-transparent" />

        <div className="absolute left-0 right-0 top-0 flex items-center justify-between p-4">
          <Link href="/library" className="rounded-full bg-black/30 p-2 text-white">
            <ChevronLeft className="h-5 w-5" />
          </Link>
          <button className="rounded-full bg-black/30 p-2 text-white">
            <MoreHorizontal className="h-5 w-5" />
          </button>
        </div>

        <div className="absolute bottom-4 left-4 right-4">
          <h1 className="text-2xl font-bold text-white">{track.title}</h1>
          <Link href={`/artist/${track.artist_id}`} className="text-sm text-white/80 hover:underline">
            {track.artist_name}
          </Link>
          <p className="text-xs text-white/60">
            {track.album_title || "Single"} • {track.release_date ? new Date(track.release_date).getFullYear() : ""} •{" "}
            {track.genre || "Musique"}
          </p>
        </div>
      </div>

      <div className="mx-auto max-w-md px-4 py-6">
        <div className="mb-6 flex items-center justify-between">
          <div className="flex items-center gap-4">
            <button
              onClick={handleLike}
              className={liked ? "text-primary" : "text-muted-foreground hover:text-foreground"}
              title={liked ? "Retirer des favoris" : "Ajouter aux favoris"}
            >
              <Heart className={`h-6 w-6 ${liked ? "fill-current" : ""}`} />
            </button>
            <button
              onClick={handleAddToPlaylist}
              className="text-muted-foreground hover:text-foreground"
              title="Ajouter à une playlist"
            >
              <Plus className="h-6 w-6" />
            </button>
            <button
              onClick={handleDownload}
              disabled={isDownloading}
              className={`${isDownloaded ? "text-primary" : "text-muted-foreground hover:text-foreground"} disabled:opacity-50`}
              title="Télécharger"
            >
              {isDownloading ? (
                <Loader2 className="h-6 w-6 animate-spin" />
              ) : isDownloaded ? (
                <Check className="h-6 w-6" />
              ) : (
                <Download className="h-6 w-6" />
              )}
            </button>
            <button onClick={handleShare} className="text-muted-foreground hover:text-foreground" title="Partager">
              <Share2 className="h-6 w-6" />
            </button>
          </div>
          <div className="flex items-center gap-2">
            {!isPurchased && (
              <Button
                variant="outline"
                size="sm"
                onClick={handlePurchase}
                disabled={isPurchasing}
                className="border-primary text-primary hover:bg-primary hover:text-primary-foreground bg-transparent"
              >
                {isPurchasing ? <Loader2 className="h-4 w-4 mr-1 animate-spin" /> : null}
                {isPurchasing ? "Achat..." : "Acheter"}
              </Button>
            )}
            <Button size="icon" className="h-14 w-14 rounded-full bg-primary" onClick={handlePlay}>
              <Play className="h-6 w-6 fill-current" />
            </Button>
          </div>
        </div>

        <div className="mb-8 grid grid-cols-3 gap-4">
          <div className="rounded-lg bg-secondary p-4 text-center">
            <p className="text-2xl font-bold text-foreground">{formatNumber(track.total_streams || 0)}</p>
            <p className="text-xs text-muted-foreground">Lectures</p>
          </div>
          <div className="rounded-lg bg-secondary p-4 text-center">
            <p className="text-2xl font-bold text-foreground">{formatNumber(likeCount)}</p>
            <p className="text-xs text-muted-foreground">J'aime</p>
          </div>
          <div className="rounded-lg bg-secondary p-4 text-center">
            <p className="text-2xl font-bold text-foreground">
              {formatDuration(Math.floor((track.duration_ms || 0) / 1000))}
            </p>
            <p className="text-xs text-muted-foreground">Durée</p>
          </div>
        </div>

        {lyricsLines.length > 0 && (
          <section className="mb-8">
            <h2 className="mb-4 text-lg font-semibold text-foreground">Paroles</h2>
            <div className="space-y-3 rounded-lg bg-secondary/50 p-6">
              {lyricsLines.map((line, index) => (
                <p key={index} className={`${line ? "text-foreground" : "h-4"} text-center leading-relaxed`}>
                  {line}
                </p>
              ))}
            </div>
          </section>
        )}

        {similarTracks.length > 0 && (
          <section>
            <h2 className="mb-4 text-lg font-semibold text-foreground">Titres similaires</h2>
            <div className="space-y-2">
              {similarTracks.map((similar) => (
                <div
                  key={similar.id}
                  className="flex items-center gap-3 rounded-lg p-2 transition-colors hover:bg-secondary"
                >
                  <Link href={`/track/${similar.id}`} className="relative h-12 w-12 overflow-hidden rounded">
                    <Image
                      src={similar.cover_url || "/placeholder.svg"}
                      alt={similar.title}
                      fill
                      className="object-cover"
                    />
                  </Link>
                  <Link href={`/track/${similar.id}`} className="flex-1">
                    <h3 className="font-medium text-foreground">{similar.title}</h3>
                    <p className="text-sm text-muted-foreground">{similar.artist_name}</p>
                  </Link>
                  <Button
                    size="icon"
                    variant="ghost"
                    className="h-10 w-10 rounded-full"
                    onClick={() => handlePlaySimilar(similar)}
                  >
                    <Play className="h-4 w-4" />
                  </Button>
                </div>
              ))}
            </div>
          </section>
        )}
      </div>

      {track && (
        <AddToPlaylistModal
          track={{
            id: track.id,
            title: track.title,
            artist: track.artist_name,
            image: track.cover_url || track.album_cover || "/placeholder.svg",
            duration: track.duration_ms,
            audioUrl: track.audio_url,
          }}
          open={showPlaylistModal}
          onOpenChange={setShowPlaylistModal}
        />
      )}

      <BottomNav />
    </div>
  )
}
