"use client"

import { useState } from "react"
import useSWR from "swr"
import { TrendingUp, Users, Music, Play, Clock, Download, Loader2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"

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

export default function AdminAnalyticsPage() {
  const [period, setPeriod] = useState("12m")

  const { data: analyticsData, isLoading: analyticsLoading } = useSWR("/api/admin/analytics", fetcher, {
    dedupingInterval: 60000,
  })
  const { data: dashboardData, isLoading: dashboardLoading } = useSWR("/api/admin/dashboard", fetcher, {
    dedupingInterval: 60000,
  })
  const { data: tracksData } = useSWR("/api/tracks?limit=5&sort=total_streams", fetcher, {
    dedupingInterval: 60000,
  })
  const { data: artistsData } = useSWR("/api/artists?limit=5", fetcher, {
    dedupingInterval: 60000,
  })

  const isLoading = analyticsLoading || dashboardLoading

  const stats = dashboardData?.stats || {}
  const topTracks = tracksData?.data || []

  // Generate chart data from real stats
  const streamData =
    analyticsData?.streamsByMonth?.length > 0
      ? analyticsData.streamsByMonth.map((m: any) => ({
          month: m.month,
          streams: Number.parseInt(m.streams) || 0,
        }))
      : [
          { month: "Jan", streams: 0 },
          { month: "Fev", streams: 0 },
          { month: "Mar", streams: 0 },
          { month: "Avr", streams: 0 },
          { month: "Mai", streams: 0 },
          { month: "Jun", streams: 0 },
        ]

  const maxStreams = Math.max(...streamData.map((d: any) => d.streams), 1)

  const formatNumber = (num: number) => {
    if (!num) return "0"
    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 min-h-[400px]">
        <Loader2 className="w-8 h-8 animate-spin text-purple-500" />
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Analytics</h1>
          <p className="text-zinc-400 text-sm">Statistiques detaillees de la plateforme</p>
        </div>
        <div className="flex items-center gap-3">
          <Select value={period} onValueChange={setPeriod}>
            <SelectTrigger className="w-40 bg-zinc-800/50 border-zinc-700 text-white">
              <SelectValue />
            </SelectTrigger>
            <SelectContent className="bg-zinc-800 border-zinc-700">
              <SelectItem value="7d">7 derniers jours</SelectItem>
              <SelectItem value="30d">30 derniers jours</SelectItem>
              <SelectItem value="12m">12 derniers mois</SelectItem>
              <SelectItem value="all">Tout</SelectItem>
            </SelectContent>
          </Select>
          <Button variant="outline" className="border-zinc-700 text-zinc-300 bg-transparent">
            <Download className="w-4 h-4 mr-2" />
            Exporter
          </Button>
        </div>
      </div>

      {/* Stats Cards - Using real data */}
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <Card className="bg-zinc-800/30 border-zinc-700/50">
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium text-zinc-400">Total Streams</CardTitle>
            <Play className="w-4 h-4 text-purple-400" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-white">{formatNumber(stats.totalStreams || 0)}</div>
            <p className="text-xs text-green-400 flex items-center mt-1">
              <TrendingUp className="w-3 h-3 mr-1" /> Données en temps réel
            </p>
          </CardContent>
        </Card>
        <Card className="bg-zinc-800/30 border-zinc-700/50">
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium text-zinc-400">Utilisateurs Actifs</CardTitle>
            <Users className="w-4 h-4 text-blue-400" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-white">{formatNumber(stats.totalUsers || 0)}</div>
            <p className="text-xs text-green-400 flex items-center mt-1">
              <TrendingUp className="w-3 h-3 mr-1" /> +{stats.newUsersThisMonth || 0} ce mois
            </p>
          </CardContent>
        </Card>
        <Card className="bg-zinc-800/30 border-zinc-700/50">
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium text-zinc-400">Abonnés Premium</CardTitle>
            <Clock className="w-4 h-4 text-cyan-400" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-white">{formatNumber(stats.premiumUsers || 0)}</div>
            <p className="text-xs text-purple-400 flex items-center mt-1">
              Revenus: {new Intl.NumberFormat("fr-FR").format(stats.monthlyRevenue || 0)} FCFA
            </p>
          </CardContent>
        </Card>
        <Card className="bg-zinc-800/30 border-zinc-700/50">
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium text-zinc-400">Total Titres</CardTitle>
            <Music className="w-4 h-4 text-pink-400" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-white">{formatNumber(stats.totalTracks || 0)}</div>
            <p className="text-xs text-green-400 flex items-center mt-1">
              <TrendingUp className="w-3 h-3 mr-1" /> +{stats.newTracksThisMonth || 0} ce mois
            </p>
          </CardContent>
        </Card>
      </div>

      {/* Charts Row */}
      <div className="grid gap-6 lg:grid-cols-2">
        {/* Streams Chart */}
        <Card className="bg-zinc-800/30 border-zinc-700/50">
          <CardHeader>
            <CardTitle className="text-white">Streams mensuels</CardTitle>
            <CardDescription className="text-zinc-400">Evolution des streams</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="h-64 flex items-end gap-2">
              {streamData.map((data: any) => (
                <div key={data.month} className="flex-1 flex flex-col items-center gap-2">
                  <div
                    className="w-full bg-gradient-to-t from-purple-600 to-purple-400 rounded-t transition-all hover:from-purple-500 hover:to-purple-300"
                    style={{ height: `${Math.max((data.streams / maxStreams) * 200, 4)}px` }}
                  />
                  <span className="text-xs text-zinc-400">{data.month}</span>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>

        {/* User Growth Chart */}
        <Card className="bg-zinc-800/30 border-zinc-700/50">
          <CardHeader>
            <CardTitle className="text-white">Résumé</CardTitle>
            <CardDescription className="text-zinc-400">Vue d'ensemble de la plateforme</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-6">
              <div className="flex justify-between items-center p-4 bg-zinc-700/30 rounded-lg">
                <div>
                  <p className="text-zinc-400 text-sm">Total utilisateurs</p>
                  <p className="text-2xl font-bold text-white">{formatNumber(stats.totalUsers || 0)}</p>
                </div>
                <Users className="w-8 h-8 text-blue-400" />
              </div>
              <div className="flex justify-between items-center p-4 bg-zinc-700/30 rounded-lg">
                <div>
                  <p className="text-zinc-400 text-sm">Revenus mensuels</p>
                  <p className="text-2xl font-bold text-white">
                    {new Intl.NumberFormat("fr-FR").format(stats.monthlyRevenue || 0)} FCFA
                  </p>
                </div>
                <TrendingUp className="w-8 h-8 text-green-400" />
              </div>
              <div className="flex justify-between items-center p-4 bg-zinc-700/30 rounded-lg">
                <div>
                  <p className="text-zinc-400 text-sm">Taux de conversion</p>
                  <p className="text-2xl font-bold text-white">
                    {stats.totalUsers > 0 ? ((stats.premiumUsers / stats.totalUsers) * 100).toFixed(1) : 0}%
                  </p>
                </div>
                <Music className="w-8 h-8 text-purple-400" />
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Bottom Row */}
      <div className="grid gap-6 lg:grid-cols-2">
        {/* Top Tracks */}
        <Card className="bg-zinc-800/30 border-zinc-700/50">
          <CardHeader>
            <CardTitle className="text-white">Top Titres</CardTitle>
            <CardDescription className="text-zinc-400">Les titres les plus écoutés</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {topTracks.length > 0 ? (
                topTracks.map((track: any, index: number) => (
                  <div key={track.id} className="flex items-center gap-4">
                    <span className="text-lg font-bold text-zinc-500 w-6">{index + 1}</span>
                    <img
                      src={track.cover_url || "/placeholder.svg?height=40&width=40&query=album"}
                      alt={track.title}
                      className="w-10 h-10 rounded object-cover"
                    />
                    <div className="flex-1 min-w-0">
                      <p className="font-medium text-white truncate">{track.title}</p>
                      <p className="text-sm text-zinc-400 truncate">{track.artist_name || "Artiste inconnu"}</p>
                    </div>
                    <div className="text-right">
                      <p className="font-medium text-white">{formatNumber(track.total_streams || 0)}</p>
                      <p className="text-xs text-zinc-400">streams</p>
                    </div>
                  </div>
                ))
              ) : (
                <p className="text-center text-zinc-400 py-8">Aucun titre disponible</p>
              )}
            </div>
          </CardContent>
        </Card>

        {/* Top Artists */}
        <Card className="bg-zinc-800/30 border-zinc-700/50">
          <CardHeader>
            <CardTitle className="text-white">Top Artistes</CardTitle>
            <CardDescription className="text-zinc-400">Artistes les plus populaires</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {artistsData?.data?.length > 0 ? (
                artistsData.data.slice(0, 5).map((artist: any, index: number) => (
                  <div key={artist.id} className="flex items-center gap-4">
                    <span className="text-lg font-bold text-zinc-500 w-6">{index + 1}</span>
                    <img
                      src={artist.avatar_url || "/placeholder.svg?height=40&width=40&query=artist"}
                      alt={artist.name}
                      className="w-10 h-10 rounded-full object-cover"
                    />
                    <div className="flex-1 min-w-0">
                      <p className="font-medium text-white truncate">{artist.name}</p>
                      <p className="text-sm text-zinc-400 truncate">{artist.genres?.[0] || "Artiste"}</p>
                    </div>
                    <div className="text-right">
                      <p className="font-medium text-white">{formatNumber(artist.monthly_listeners || 0)}</p>
                      <p className="text-xs text-zinc-400">auditeurs</p>
                    </div>
                  </div>
                ))
              ) : (
                <p className="text-center text-zinc-400 py-8">Aucun artiste disponible</p>
              )}
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
