"use client"

import Image from "next/image"
import Link from "next/link"
import { useParams } from "next/navigation"
import { ChevronLeft, MoreHorizontal, Play, Pause, Shuffle, Heart, Download, Share2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { BottomNav } from "@/components/bottom-nav"
import { usePlayer } from "@/components/player-provider"
import useSWR from "swr"
import { Loader2 } from "lucide-react"
import { useState } from "react"
import { useToast } from "@/components/ui/use-toast"

const fetcher = (url: string) => fetch(url).then((res) => res.json())

const formatDuration = (seconds: number) => {
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins}:${secs.toString().padStart(2, "0")}`
}

export default function AlbumPage() {
  const { id } = useParams<{ id: string }>()

  const { data: albumData, isLoading } = useSWR(id ? `/api/albums/${id}` : null, fetcher)
  const { data: user } = useSWR("/api/auth/me", fetcher)

  const album = albumData?.data

  const [isPurchasing, setIsPurchasing] = useState(false)
  const [isPurchased, setIsPurchased] = useState(false)
  const { toast } = useToast()

  const {
    playTrack,
    playAlbum,
    currentTrack,
    isPlaying,
    togglePlay,
    toggleLike,
    isLiked,
    shuffleEnabled,
    toggleShuffle,
  } = usePlayer()

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

    try {
      setIsPurchasing(true)

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

      if (response.ok) {
        const data = await response.json()
        setIsPurchased(true)
        toast({
          title: "Achat réussi",
          description: `Vous avez acheté l'album "${album.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)
    }
  }

  if (isLoading) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <Loader2 className="w-8 h-8 animate-spin text-primary" />
      </div>
    )
  }

  if (!album) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <div className="text-center">
          <p className="text-muted-foreground mb-4">Album non trouvé</p>
          <Link href="/">
            <Button>Retour à l'accueil</Button>
          </Link>
        </div>
      </div>
    )
  }

  const tracks = album.tracks || []
  const totalDuration = tracks.reduce((acc: number, t: any) => acc + (t.duration_ms || 0) / 1000, 0)
  const isAlbumPlaying = tracks.some((t: any) => t.id === currentTrack?.id) && isPlaying

  const handlePlayAlbum = () => {
    if (isAlbumPlaying) {
      togglePlay()
    } else {
      playAlbum(
        tracks.map((t: any) => ({
          id: t.id,
          title: t.title,
          artist: album.artist_name || "Unknown",
          image: album.cover_url || "/abstract-music-album.png",
          duration: Math.floor((t.duration_ms || 0) / 1000),
          audioUrl: t.audio_url,
        })),
        0,
      )
    }
  }

  const handleShufflePlay = () => {
    if (!shuffleEnabled) toggleShuffle()
    playAlbum(
      tracks.map((t: any) => ({
        id: t.id,
        title: t.title,
        artist: album.artist_name || "Unknown",
        image: album.cover_url || "/abstract-music-album.png",
        duration: Math.floor((t.duration_ms || 0) / 1000),
        audioUrl: t.audio_url,
      })),
      0,
    )
  }

  return (
    <div className="min-h-screen bg-background pb-24">
      {/* Hero Section */}
      <div className="relative">
        <div className="absolute inset-0 h-80">
          <Image
            src={album.cover_url || "/placeholder.svg?height=400&width=400&query=album"}
            alt="Album Art"
            fill
            className="object-cover opacity-30 blur-xl"
          />
          <div className="absolute inset-0 bg-gradient-to-b from-transparent to-background" />
        </div>

        {/* Header */}
        <div className="relative z-10 flex items-center justify-between p-4">
          <Link href="/" className="text-foreground hover:text-primary">
            <ChevronLeft className="h-6 w-6" />
          </Link>
          <button className="text-foreground hover:text-primary">
            <MoreHorizontal className="h-6 w-6" />
          </button>
        </div>

        {/* Album Info */}
        <div className="relative z-10 flex flex-col items-center px-4 pb-6 pt-4">
          <div className="relative mb-4 h-48 w-48 overflow-hidden rounded-xl shadow-2xl">
            <Image
              src={album.cover_url || "/placeholder.svg?height=300&width=300&query=album"}
              alt={album.title}
              fill
              className="object-cover"
            />
          </div>
          <h1 className="mb-1 text-2xl font-bold text-foreground">{album.title}</h1>
          <p className="mb-1 text-muted-foreground">{album.artist_name}</p>
          <p className="text-sm text-muted-foreground">
            {new Date(album.release_date).getFullYear()} • {tracks.length} titres • {Math.floor(totalDuration / 60)} min
          </p>
        </div>
      </div>

      <div className="mx-auto max-w-md px-4">
        {/* Action Buttons */}
        <div className="mb-6 flex items-center justify-between">
          <div className="flex items-center gap-4">
            <button className="text-muted-foreground hover:text-primary">
              <Heart className="h-6 w-6" />
            </button>
            <button className="text-muted-foreground hover:text-primary">
              <Download className="h-6 w-6" />
            </button>
            <button className="text-muted-foreground hover:text-primary">
              <Share2 className="h-6 w-6" />
            </button>
          </div>
          <div className="flex items-center gap-3">
            {!isPurchased && (
              <Button
                variant="outline"
                size="sm"
                onClick={handlePurchaseAlbum}
                disabled={isPurchasing}
                className="border-primary text-primary hover:bg-primary hover:text-primary-foreground bg-transparent"
              >
                {isPurchasing ? "Achat..." : "Acheter l'album"}
              </Button>
            )}
            <button
              onClick={handleShufflePlay}
              className={`transition-colors ${shuffleEnabled ? "text-primary" : "text-muted-foreground hover:text-foreground"}`}
            >
              <Shuffle className="h-6 w-6" />
            </button>
            <Button size="icon" className="h-12 w-12 rounded-full" onClick={handlePlayAlbum}>
              {isAlbumPlaying ? <Pause className="h-6 w-6" /> : <Play className="h-6 w-6 ml-0.5" />}
            </Button>
          </div>
        </div>

        {/* Track List */}
        <div className="space-y-1">
          {tracks.map((track: any, index: number) => {
            const isCurrentTrack = currentTrack?.id === track.id
            const trackIsPlaying = isCurrentTrack && isPlaying

            return (
              <button
                key={track.id}
                onClick={() =>
                  isCurrentTrack
                    ? togglePlay()
                    : playTrack({
                        id: track.id,
                        title: track.title,
                        artist: album.artist_name,
                        image: track.cover_url || album.cover_url || "/abstract-music-album.png",
                        cover_url: track.cover_url || album.cover_url,
                        album_cover: album.cover_url,
                        duration: Math.floor((track.duration_ms || 0) / 1000),
                        audioUrl: track.audio_url,
                        artistId: album.artist_id,
                        albumId: album.id,
                      })
                }
                className={`flex w-full items-center gap-4 rounded-lg p-3 transition-colors hover:bg-secondary text-left ${
                  isCurrentTrack ? "bg-secondary" : ""
                }`}
              >
                <span
                  className={`w-6 text-center text-sm ${isCurrentTrack ? "text-primary" : "text-muted-foreground"}`}
                >
                  {trackIsPlaying ? (
                    <span className="flex justify-center gap-0.5">
                      <span className="h-3 w-0.5 animate-pulse bg-primary" />
                      <span className="h-4 w-0.5 animate-pulse bg-primary" style={{ animationDelay: "150ms" }} />
                      <span className="h-2 w-0.5 animate-pulse bg-primary" style={{ animationDelay: "300ms" }} />
                    </span>
                  ) : (
                    index + 1
                  )}
                </span>
                <div className="flex-1">
                  <p className={`font-medium ${isCurrentTrack ? "text-primary" : "text-foreground"}`}>{track.title}</p>
                </div>
                <button
                  onClick={(e) => {
                    e.stopPropagation()
                    toggleLike(track.id)
                  }}
                  className={`p-1 ${isLiked(track.id) ? "text-primary" : "text-muted-foreground opacity-0 group-hover:opacity-100"}`}
                >
                  <Heart className={`h-4 w-4 ${isLiked(track.id) ? "fill-current" : ""}`} />
                </button>
                <span className="text-sm text-muted-foreground">
                  {formatDuration(Math.floor((track.duration_ms || 0) / 1000))}
                </span>
              </button>
            )
          })}
        </div>

        {/* Album Info Footer */}
        <div className="mt-8 space-y-2 text-sm text-muted-foreground">
          <p>
            {new Date(album.release_date).toLocaleDateString("fr-FR", {
              day: "numeric",
              month: "long",
              year: "numeric",
            })}
          </p>
          <p>
            {tracks.length} titres, {Math.floor(totalDuration / 60)} minutes
          </p>
          {album.label && (
            <p className="text-xs">
              &#8471; {new Date(album.release_date).getFullYear()} {album.label}
            </p>
          )}
        </div>
      </div>

      <BottomNav />
    </div>
  )
}
