"use client"

import { Users, UserPlus, Globe, Clock, Heart, Loader2, Music, TrendingUp } from "lucide-react"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { useAuth } from "@/components/auth-provider"
import useSWR from "swr"

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

export default function ArtistAudiencePage() {
  const { user } = useAuth()
  const artistId = user?.artistId

  const { data, isLoading } = useSWR(artistId ? `/api/artist/audience?artistId=${artistId}` : null, fetcher)

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

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="w-8 h-8 animate-spin text-purple-500" />
      </div>
    )
  }

  const {
    followers = 0,
    newFollowers = 0,
    countries = 0,
    totalListeners = 0,
    monthlyListeners = 0,
    topCities = [],
    listeningHabits = [],
    topTracks = [],
    recentFollowers = [],
    ageGroups = [],
    genderData = [],
  } = data || {}

  const loyaltyRate = totalListeners > 0 ? Math.round((followers / totalListeners) * 100) : 0

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold text-white">Audience</h1>
        <p className="text-zinc-400">Decouvrez qui ecoute votre musique</p>
      </div>

      {/* Overview Stats */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <Card className="bg-zinc-800/50 border-zinc-700">
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-blue-500/20 rounded-lg flex items-center justify-center">
                <Users className="w-5 h-5 text-blue-400" />
              </div>
              <div>
                <p className="text-zinc-400 text-sm">Followers</p>
                <p className="text-xl font-bold text-white">{formatNumber(followers)}</p>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="bg-zinc-800/50 border-zinc-700">
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-green-500/20 rounded-lg flex items-center justify-center">
                <UserPlus className="w-5 h-5 text-green-400" />
              </div>
              <div>
                <p className="text-zinc-400 text-sm">Nouveaux (7j)</p>
                <p className="text-xl font-bold text-white">+{formatNumber(newFollowers)}</p>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="bg-zinc-800/50 border-zinc-700">
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-purple-500/20 rounded-lg flex items-center justify-center">
                <TrendingUp className="w-5 h-5 text-purple-400" />
              </div>
              <div>
                <p className="text-zinc-400 text-sm">Auditeurs (30j)</p>
                <p className="text-xl font-bold text-white">{formatNumber(monthlyListeners)}</p>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="bg-zinc-800/50 border-zinc-700">
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-pink-500/20 rounded-lg flex items-center justify-center">
                <Globe className="w-5 h-5 text-pink-400" />
              </div>
              <div>
                <p className="text-zinc-400 text-sm">Pays</p>
                <p className="text-xl font-bold text-white">{countries}</p>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      <div className="grid lg:grid-cols-3 gap-6">
        {/* Top Tracks */}
        <Card className="bg-zinc-800/50 border-zinc-700 lg:col-span-2">
          <CardHeader>
            <CardTitle className="text-white flex items-center gap-2">
              <Music className="w-5 h-5 text-purple-400" />
              Titres populaires
            </CardTitle>
          </CardHeader>
          <CardContent>
            {topTracks.length === 0 ? (
              <p className="text-zinc-400 text-center py-4">Pas de donnees disponibles</p>
            ) : (
              <div className="space-y-4">
                {topTracks.map((track: any, index: number) => (
                  <div key={track.id} className="flex items-center gap-4">
                    <span className="text-zinc-500 w-6 text-center font-medium">{index + 1}</span>
                    <img
                      src={track.cover_url || "/placeholder.svg?height=48&width=48&query=music"}
                      alt={track.title}
                      className="w-12 h-12 rounded-lg object-cover"
                    />
                    <div className="flex-1 min-w-0">
                      <p className="text-white font-medium truncate">{track.title}</p>
                      <p className="text-zinc-400 text-sm">
                        {formatNumber(track.total_streams || 0)} streams • {formatNumber(track.unique_listeners || 0)}{" "}
                        auditeurs
                      </p>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>

        {/* Recent Followers */}
        <Card className="bg-zinc-800/50 border-zinc-700">
          <CardHeader>
            <CardTitle className="text-white flex items-center gap-2">
              <Heart className="w-5 h-5 text-pink-400" />
              Nouveaux followers
            </CardTitle>
          </CardHeader>
          <CardContent>
            {recentFollowers.length === 0 ? (
              <p className="text-zinc-400 text-center py-4">Aucun follower recent</p>
            ) : (
              <div className="space-y-3">
                {recentFollowers.slice(0, 5).map((follower: any) => (
                  <div key={follower.id} className="flex items-center gap-3">
                    <img
                      src={follower.avatar_url || "/placeholder.svg?height=32&width=32&query=user"}
                      alt={follower.name}
                      className="w-8 h-8 rounded-full object-cover"
                    />
                    <div className="flex-1 min-w-0">
                      <p className="text-white text-sm font-medium truncate">{follower.name}</p>
                      <p className="text-zinc-500 text-xs">
                        {new Date(follower.created_at).toLocaleDateString("fr-FR")}
                      </p>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      <div className="grid lg:grid-cols-2 gap-6">
        {/* Top Countries */}
        <Card className="bg-zinc-800/50 border-zinc-700">
          <CardHeader>
            <CardTitle className="text-white">Pays principaux</CardTitle>
          </CardHeader>
          <CardContent>
            {topCities.length === 0 ? (
              <p className="text-zinc-400 text-center py-4">Pas de donnees disponibles</p>
            ) : (
              <div className="space-y-4">
                {topCities.map((city: any, index: number) => (
                  <div key={index} className="flex items-center gap-4">
                    <span className="text-zinc-500 w-6 text-center">{index + 1}</span>
                    <div className="flex-1">
                      <p className="text-white font-medium">{city.city}</p>
                    </div>
                    <p className="text-zinc-400">{Number(city.listeners).toLocaleString()} auditeurs</p>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>

        {/* Listening Habits */}
        <Card className="bg-zinc-800/50 border-zinc-700">
          <CardHeader>
            <CardTitle className="text-white flex items-center gap-2">
              <Clock className="w-5 h-5 text-purple-400" />
              Heures d'ecoute
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {(listeningHabits.length > 0
                ? listeningHabits
                : [
                    { time: "Matin (6h-12h)", percentage: 22 },
                    { time: "Apres-midi (12h-18h)", percentage: 28 },
                    { time: "Soiree (18h-0h)", percentage: 38 },
                    { time: "Nuit (0h-6h)", percentage: 12 },
                  ]
              ).map((habit: any, index: number) => (
                <div key={index} className="space-y-2">
                  <div className="flex items-center justify-between">
                    <span className="text-zinc-300">{habit.time}</span>
                    <span className="text-white font-medium">{habit.percentage}%</span>
                  </div>
                  <div className="h-3 bg-zinc-700 rounded-full overflow-hidden">
                    <div
                      className="h-full bg-gradient-to-r from-blue-600 to-purple-500 rounded-full"
                      style={{ width: `${habit.percentage}%` }}
                    ></div>
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>

        {/* Age Groups */}
        <Card className="bg-zinc-800/50 border-zinc-700">
          <CardHeader>
            <CardTitle className="text-white">Tranches d'age</CardTitle>
          </CardHeader>
          <CardContent>
            {ageGroups.length === 0 ? (
              <p className="text-zinc-400 text-center py-4">Pas de donnees disponibles</p>
            ) : (
              <div className="space-y-4">
                {ageGroups.map((group: any, index: number) => (
                  <div key={index} className="space-y-2">
                    <div className="flex items-center justify-between">
                      <span className="text-zinc-300">{group.range} ans</span>
                      <span className="text-white font-medium">{group.percentage}%</span>
                    </div>
                    <div className="h-3 bg-zinc-700 rounded-full overflow-hidden">
                      <div
                        className="h-full bg-gradient-to-r from-purple-600 to-pink-500 rounded-full"
                        style={{ width: `${group.percentage}%` }}
                      ></div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>

        {/* Gender Distribution */}
        <Card className="bg-zinc-800/50 border-zinc-700">
          <CardHeader>
            <CardTitle className="text-white">Repartition par genre</CardTitle>
          </CardHeader>
          <CardContent>
            {genderData.length === 0 ? (
              <p className="text-zinc-400 text-center py-4">Pas de donnees disponibles</p>
            ) : (
              <div className="flex items-center justify-center gap-8">
                {genderData.map((item: any, index: number) => (
                  <div key={index} className="text-center">
                    <div
                      className={`w-24 h-24 rounded-full flex items-center justify-center mb-2 ${
                        index === 0 ? "bg-pink-500/20" : index === 1 ? "bg-blue-500/20" : "bg-purple-500/20"
                      }`}
                    >
                      <span
                        className={`text-2xl font-bold ${
                          index === 0 ? "text-pink-400" : index === 1 ? "text-blue-400" : "text-purple-400"
                        }`}
                      >
                        {item.percentage}%
                      </span>
                    </div>
                    <p className="text-zinc-300">{item.gender}</p>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
