"use client"

import Image from "next/image"
import Link from "next/link"
import { useParams, useRouter } from "next/navigation"
import { ChevronLeft, MoreHorizontal, Play, Pause, Share2, Heart, Loader2, Check } from "lucide-react"
import { Button } from "@/components/ui/button"
import { BottomNav } from "@/components/bottom-nav"
import { SectionHeader } from "@/components/section-header"
import { usePlayer } from "@/components/player-provider"
import { useUser } from "@/components/user-provider"
import { useAuth } from "@/components/auth-provider"
import useSWR from "swr"
import { useState, useEffect } from "react"

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 ArtistPage() {
  const { id } = useParams()
  const artistId = Array.isArray(id) ? id[0] : id
  const [isFollowLoading, setIsFollowLoading] = useState(false)
  const [localIsFollowing, setLocalIsFollowing] = useState<boolean | null>(null)
  const router = useRouter()



  const {
    data: artistData,
    isLoading,
    error: artistError,
    mutate,
  } = useSWR(artistId ? `/api/artists/${artistId}` : null, fetcher)



  const { data: followStatus, mutate: mutateFollowStatus } = useSWR(
    artistId && artistData?.data?.user?.id ? `/api/artists/${artistId}/follow?userId=${artistData.data.user.id}` : null,
    fetcher,
  )

  const artist = artistData?.data

  const { playTrack, playAlbum, currentTrack, isPlaying, togglePlay, toggleLike, isLiked } = usePlayer()
  const { toggleFollowArtist } = useUser()
  const { user, isLoading: isAuthLoading } = useAuth()

  useEffect(() => {
    if (followStatus?.following !== undefined) {
      setLocalIsFollowing(followStatus.following)
    }
  }, [followStatus?.following])

  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 (!artist) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <div className="text-center">
          <p className="text-muted-foreground mb-4">Artiste non trouvé</p>
          <Link href="/artists">
            <Button>Retour aux artistes</Button>
          </Link>
        </div>
      </div>
    )
  }

  const tracks = artist.tracks || []
  const isFollowing = localIsFollowing ?? followStatus?.following ?? false
  const isArtistPlaying = tracks.some((t: any) => t.id === currentTrack?.id) && isPlaying

  const handlePlayArtist = () => {
    if (isArtistPlaying) {
      togglePlay()
    } else {
      playAlbum(
        tracks.map((t: any) => ({
          id: t.id,
          title: t.title,
          artist: artist.name,
          image: t.cover_url || artist.profile_image || "/abstract-music-album.png",
          cover_url: t.cover_url,
          album_cover: t.album_cover,
          duration: Math.floor((t.duration_ms || 0) / 1000),
          audioUrl: t.audio_url,
          artistId: artist.id,
        })),
        0,
      )
    }
  }

  const handleFollow = async () => {
    if (isAuthLoading) {
      return
    }

    if (!user) {
      router.push("/login?redirect=" + encodeURIComponent(`/artist/${artistId}`))
      return
    }

    setIsFollowLoading(true)
    const previousState = isFollowing
    setLocalIsFollowing(!isFollowing)

    try {
      await toggleFollowArtist(artistId)
      await Promise.all([mutate(), mutateFollowStatus()])
    } catch (error) {
      setLocalIsFollowing(previousState)
    } finally {
      setIsFollowLoading(false)
    }
  }

  return (
    <div className="min-h-screen bg-background pb-24">
      {/* Hero Section */}
      <div className="relative h-72">
        <Image
          src={artist.profile_image || "/placeholder.svg?height=400&width=400&query=artist"}
          alt={artist.name}
          fill
          className="object-cover"
          priority
        />
        <div className="absolute inset-0 bg-gradient-to-t from-background via-background/50 to-transparent" />

        {/* Header */}
        <div className="absolute left-0 right-0 top-0 z-10 flex items-center justify-between p-4">
          <Link href="/artists" className="rounded-full bg-black/30 p-2 text-white hover:bg-black/50">
            <ChevronLeft className="h-5 w-5" />
          </Link>
          <div className="flex items-center gap-2">
            <button className="rounded-full bg-black/30 p-2 text-white hover:bg-black/50">
              <Share2 className="h-5 w-5" />
            </button>
            <button className="rounded-full bg-black/30 p-2 text-white hover:bg-black/50">
              <MoreHorizontal className="h-5 w-5" />
            </button>
          </div>
        </div>

        {/* Artist Name & Actions */}
        <div className="absolute bottom-6 left-0 right-0 px-4">
          <h1 className="text-3xl font-bold text-white mb-1">{artist.name}</h1>
          <p className="text-white/80 text-sm mb-4">{artist.follower_count || artist.total_followers || 0} abonnés</p>
          <div className="flex items-center gap-3">
            <Button
              variant={isFollowing ? "secondary" : "outline"}
              className={`rounded-full min-w-[100px] ${isFollowing ? "bg-primary/20 text-primary hover:bg-primary/30" : "border-white/50 bg-white/10 text-white hover:bg-white/20"}`}
              onClick={handleFollow}
              disabled={isFollowLoading || isAuthLoading}
            >
              {isFollowLoading ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : isFollowing ? (
                <>
                  <Check className="h-4 w-4 mr-1" />
                  Abonné
                </>
              ) : (
                "Suivre"
              )}
            </Button>
            <Button size="icon" className="h-12 w-12 rounded-full" onClick={handlePlayArtist}>
              {isArtistPlaying ? <Pause className="h-6 w-6" /> : <Play className="h-6 w-6 ml-0.5" />}
            </Button>
          </div>
        </div>
      </div>

      <div className="mx-auto max-w-md px-4 py-6">
        {/* Top Tracks */}
        <section className="mb-8">
          <SectionHeader title="Titres populaires" />
          {tracks.length === 0 ? (
            <div className="text-center py-8 text-muted-foreground">
              <p>Aucun titre disponible</p>
            </div>
          ) : (
            <div className="mt-4 space-y-1">
              {tracks.slice(0, 10).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: artist.name,
                            image: track.cover_url || artist.profile_image || "/abstract-music-album.png",
                            cover_url: track.cover_url,
                            album_cover: track.album_cover,
                            duration: Math.floor((track.duration_ms || 0) / 1000),
                            audioUrl: track.audio_url,
                            artistId: artist.id,
                          })
                    }
                    className={`flex w-full items-center gap-3 rounded-lg p-2 transition-colors hover:bg-secondary text-left ${isCurrentTrack ? "bg-secondary/50" : ""}`}
                  >
                    <span
                      className={`w-5 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>
                      ) : (
                        index + 1
                      )}
                    </span>
                    <div className="relative h-10 w-10 overflow-hidden rounded">
                      <Image
                        src={
                          track.cover_url || artist.profile_image || "/placeholder.svg?height=60&width=60&query=track"
                        }
                        alt={track.title}
                        fill
                        className="object-cover"
                      />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className={`truncate 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"}`}
                    >
                      <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>
          )}
        </section>

        {artist.bio && (
          <section className="mb-8">
            <SectionHeader title="À propos" />
            <p className="mt-4 text-muted-foreground">{artist.bio}</p>
          </section>
        )}
      </div>

      <BottomNav />
    </div>
  )
}
