"use client"

import type React from "react"

import Image from "next/image"
import Link from "next/link"
import { ChevronLeft, UserPlus, Loader2, Check } from "lucide-react"
import { BottomNav } from "@/components/bottom-nav"
import { SectionHeader } from "@/components/section-header"
import { useUser } from "@/components/user-provider"
import { useAuth } from "@/components/auth-provider"
import { useRouter } from "next/navigation"
import useSWR from "swr"
import { useState } from "react"

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

function ArtistCard({
  artist,
  showFollow = false,
  onFollowChange,
}: { artist: any; showFollow?: boolean; onFollowChange?: () => void }) {
  const { user, isLoading: isAuthLoading } = useAuth()
  const { isFollowingArtist, toggleFollowArtist } = useUser()
  const router = useRouter()
  const [isLoadingFollow, setIsLoadingFollow] = useState(false)

  const isFollowing = isFollowingArtist(artist.id)

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

    if (isAuthLoading) return

    if (!user) {
      router.push("/login?redirect=/artists")
      return
    }

    setIsLoadingFollow(true)
    try {
      await toggleFollowArtist(artist.id)
      if (onFollowChange) {
        onFollowChange()
      }
    } finally {
      setIsLoadingFollow(false)
    }
  }

  return (
    <Link href={`/artist/${artist.id}`}>
      <div className="flex items-center gap-3 rounded-lg p-2 transition-colors hover:bg-secondary">
        <div className="relative h-14 w-14 overflow-hidden rounded-full">
          <Image
            src={
              artist.avatar_url ||
              artist.profile_image ||
              artist.image ||
              "/placeholder.svg?height=60&width=60&query=artist"
            }
            alt={artist.name}
            fill
            className="object-cover"
          />
        </div>
        <div className="flex-1">
          <h3 className="font-medium text-foreground">{artist.name}</h3>
          <p className="text-sm text-muted-foreground">
            {artist.follower_count || 0} abonné{Number(artist.follower_count) !== 1 ? "s" : ""}
          </p>
        </div>
        {showFollow && (
          <button
            onClick={handleFollow}
            disabled={isLoadingFollow}
            className={`rounded-full border px-4 py-1 text-sm transition-colors ${
              isFollowing
                ? "border-primary bg-primary/10 text-primary"
                : "border-primary text-primary hover:bg-primary hover:text-primary-foreground"
            }`}
          >
            {isLoadingFollow ? (
              <Loader2 className="h-4 w-4 animate-spin" />
            ) : isFollowing ? (
              <span className="flex items-center gap-1">
                <Check className="h-3 w-3" />
                Suivi
              </span>
            ) : (
              "Suivre"
            )}
          </button>
        )}
      </div>
    </Link>
  )
}

export default function ArtistsPage() {
  const { data: artistsData, isLoading, mutate: refreshArtists } = useSWR("/api/artists", fetcher)

  const artists = artistsData?.data || []

  const handleFollowChange = () => {
    // Refresh artists data to get updated follower counts
    refreshArtists()
  }

  return (
    <div className="min-h-screen bg-background pb-24">
      <div className="mx-auto max-w-md px-4 py-6">
        {/* Header */}
        <div className="mb-6 flex items-center justify-between">
          <div className="flex items-center gap-4">
            <Link href="/library" className="text-foreground hover:text-primary">
              <ChevronLeft className="h-6 w-6" />
            </Link>
            <h1 className="text-xl font-bold text-foreground">Artistes</h1>
          </div>
          <button className="rounded-full p-2 text-muted-foreground hover:text-foreground">
            <UserPlus className="h-5 w-5" />
          </button>
        </div>

        {isLoading ? (
          <div className="flex justify-center py-12">
            <Loader2 className="w-8 h-8 animate-spin text-primary" />
          </div>
        ) : artists.length === 0 ? (
          <div className="text-center py-12 text-muted-foreground">
            <p>Aucun artiste trouvé</p>
          </div>
        ) : (
          <>
            {/* All Artists */}
            <section className="mb-8">
              <SectionHeader title="Tous les artistes" />
              <div className="mt-4 space-y-1">
                {artists.map((artist: any) => (
                  <ArtistCard key={artist.id} artist={artist} showFollow onFollowChange={handleFollowChange} />
                ))}
              </div>
            </section>
          </>
        )}
      </div>

      <BottomNav />
    </div>
  )
}
