"use client"
import { Play, TrendingUp, Users, Music, DollarSign, Loader2 } from "lucide-react"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import Link from "next/link"
import { useAuth } from "@/components/auth-provider"
import useSWR from "swr"

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

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

  const { data, error, isLoading } = useSWR(artistId ? `/api/artist/stats?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 stats = data?.stats || { totalTracks: 0, totalAlbums: 0, totalStreams: 0, followers: 0, monthlyListeners: 0 }
  const topTracks = data?.topTracks || []
  const recentActivity = data?.recentActivity || []

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-white">Bonjour, {user?.name}!</h1>
          <p className="text-zinc-400">Voici un apercu de vos performances</p>
        </div>
        <Link href="/artist/upload">
          <Button className="bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-700 hover:to-pink-700">
            <Music className="w-4 h-4 mr-2" />
            Uploader un titre
          </Button>
        </Link>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <Card className="bg-zinc-800/50 border-zinc-700">
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-zinc-400 text-sm">Total streams</p>
                <p className="text-2xl font-bold text-white mt-1">{formatNumber(stats.totalStreams)}</p>
              </div>
              <div className="w-12 h-12 bg-purple-500/20 rounded-xl flex items-center justify-center">
                <Play className="w-6 h-6 text-purple-400" />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="bg-zinc-800/50 border-zinc-700">
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-zinc-400 text-sm">Auditeurs mensuels</p>
                <p className="text-2xl font-bold text-white mt-1">{formatNumber(stats.monthlyListeners)}</p>
              </div>
              <div className="w-12 h-12 bg-blue-500/20 rounded-xl flex items-center justify-center">
                <Users className="w-6 h-6 text-blue-400" />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="bg-zinc-800/50 border-zinc-700">
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-zinc-400 text-sm">Followers</p>
                <p className="text-2xl font-bold text-white mt-1">{formatNumber(stats.followers)}</p>
              </div>
              <div className="w-12 h-12 bg-green-500/20 rounded-xl flex items-center justify-center">
                <Users className="w-6 h-6 text-green-400" />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="bg-zinc-800/50 border-zinc-700">
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-zinc-400 text-sm">Total de titres</p>
                <p className="text-2xl font-bold text-white mt-1">{stats.totalTracks}</p>
                <p className="text-zinc-400 text-xs flex items-center mt-1">
                  <Music className="w-3 h-3 mr-1" />
                  {stats.totalAlbums} albums
                </p>
              </div>
              <div className="w-12 h-12 bg-pink-500/20 rounded-xl flex items-center justify-center">
                <Music className="w-6 h-6 text-pink-400" />
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      <div className="grid lg:grid-cols-3 gap-6">
        {/* Top Tracks */}
        <div className="lg:col-span-2">
          <Card className="bg-zinc-800/50 border-zinc-700">
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle className="text-white">Titres populaires</CardTitle>
              <Link href="/artist/tracks" className="text-sm text-purple-400 hover:text-purple-300">
                Voir tout
              </Link>
            </CardHeader>
            <CardContent>
              {topTracks.length === 0 ? (
                <div className="text-center py-8">
                  <Music className="w-12 h-12 text-zinc-600 mx-auto mb-4" />
                  <p className="text-zinc-400">Aucun titre pour le moment</p>
                  <Link href="/artist/upload">
                    <Button className="mt-4 bg-purple-600 hover:bg-purple-700">Uploader votre premier titre</Button>
                  </Link>
                </div>
              ) : (
                <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-4 text-sm">{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.play_count || 0)} streams</p>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </div>

        {/* Recent Activity */}
        <div>
          <Card className="bg-zinc-800/50 border-zinc-700">
            <CardHeader>
              <CardTitle className="text-white">Activite recente</CardTitle>
            </CardHeader>
            <CardContent>
              {recentActivity.length === 0 ? (
                <p className="text-zinc-400 text-center py-4">Aucune activite recente</p>
              ) : (
                <div className="space-y-4">
                  {recentActivity.slice(0, 5).map((activity: any, index: number) => (
                    <div key={index} className="flex items-start gap-3">
                      <div className="w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 bg-purple-500/20">
                        <Play className="w-4 h-4 text-purple-400" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="text-zinc-300 text-sm">{activity.description}</p>
                        <p className="text-zinc-500 text-xs">{formatNumber(activity.value || 0)} streams</p>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </div>
      </div>

      {/* Quick Actions */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <Link href="/artist/upload">
          <Card className="bg-zinc-800/50 border-zinc-700 hover:border-purple-500/50 transition-colors cursor-pointer">
            <CardContent className="p-4 flex items-center gap-3">
              <div className="w-10 h-10 bg-purple-500/20 rounded-lg flex items-center justify-center">
                <Music className="w-5 h-5 text-purple-400" />
              </div>
              <div>
                <p className="text-white font-medium">Uploader</p>
                <p className="text-zinc-400 text-xs">Nouveau titre</p>
              </div>
            </CardContent>
          </Card>
        </Link>
        <Link href="/artist/analytics">
          <Card className="bg-zinc-800/50 border-zinc-700 hover:border-purple-500/50 transition-colors cursor-pointer">
            <CardContent className="p-4 flex items-center gap-3">
              <div className="w-10 h-10 bg-blue-500/20 rounded-lg flex items-center justify-center">
                <TrendingUp className="w-5 h-5 text-blue-400" />
              </div>
              <div>
                <p className="text-white font-medium">Statistiques</p>
                <p className="text-zinc-400 text-xs">Performances</p>
              </div>
            </CardContent>
          </Card>
        </Link>
        <Link href="/artist/audience">
          <Card className="bg-zinc-800/50 border-zinc-700 hover:border-purple-500/50 transition-colors cursor-pointer">
            <CardContent className="p-4 flex items-center gap-3">
              <div className="w-10 h-10 bg-green-500/20 rounded-lg flex items-center justify-center">
                <Users className="w-5 h-5 text-green-400" />
              </div>
              <div>
                <p className="text-white font-medium">Audience</p>
                <p className="text-zinc-400 text-xs">Vos fans</p>
              </div>
            </CardContent>
          </Card>
        </Link>
        <Link href="/artist/earnings">
          <Card className="bg-zinc-800/50 border-zinc-700 hover:border-purple-500/50 transition-colors cursor-pointer">
            <CardContent className="p-4 flex items-center gap-3">
              <div className="w-10 h-10 bg-yellow-500/20 rounded-lg flex items-center justify-center">
                <DollarSign className="w-5 h-5 text-yellow-400" />
              </div>
              <div>
                <p className="text-white font-medium">Revenus</p>
                <p className="text-zinc-400 text-xs">Gains</p>
              </div>
            </CardContent>
          </Card>
        </Link>
      </div>
    </div>
  )
}
