"use client"

import type React from "react"
import { Users, Music, Play, TrendingUp, TrendingDown, ArrowUpRight, MoreHorizontal, Eye, Loader2 } from "lucide-react"
import Image from "next/image"
import Link from "next/link"
import useSWR from "swr"

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

export default function AdminDashboard() {
  const { data, isLoading, error } = useSWR("/api/admin/dashboard", 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.toLocaleString()
  }

  const formatFCFA = (amount: number) => {
    return new Intl.NumberFormat("fr-FR").format(amount) + " FCFA"
  }

  const dashboardStats = data?.stats
    ? [
        {
          name: "Utilisateurs Actifs",
          value: formatNumber(data.stats.totalUsers),
          change: `+${data.stats.newUsersThisMonth} ce mois`,
          trend: data.stats.newUsersThisMonth > 0 ? "up" : "neutral",
          icon: Users,
          color: "from-blue-500 to-cyan-500",
        },
        {
          name: "Titres Totaux",
          value: formatNumber(data.stats.totalTracks),
          change: `+${data.stats.newTracksThisMonth} ce mois`,
          trend: data.stats.newTracksThisMonth > 0 ? "up" : "neutral",
          icon: Music,
          color: "from-purple-500 to-pink-500",
        },
        {
          name: "Écoutes Totales",
          value: formatNumber(data.stats.totalStreams),
          change:
            data.stats.streamsChange !== 0
              ? `${data.stats.streamsChange > 0 ? "+" : ""}${data.stats.streamsChange}%`
              : "0%",
          trend: data.stats.streamsChange >= 0 ? "up" : "down",
          icon: Play,
          color: "from-orange-500 to-red-500",
        },
        {
          name: "Revenus Mensuels",
          value: formatFCFA(data.stats.monthlyRevenue),
          change:
            data.stats.revenueChange !== 0
              ? `${data.stats.revenueChange > 0 ? "+" : ""}${data.stats.revenueChange}%`
              : `${data.stats.premiumUsers} premium`,
          trend: data.stats.revenueChange >= 0 ? "up" : "down",
          icon: TrendingUp,
          color: "from-green-500 to-emerald-500",
        },
      ]
    : []

  const topTracks = data?.topTracks || []
  const recentUsers = data?.recentUsers || []
  const recentActivity = data?.recentActivity || []

  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>
    )
  }

  if (error) {
    console.error("[v0] Dashboard error:", error)
    return (
      <div className="flex flex-col items-center justify-center min-h-[400px] gap-4">
        <p className="text-red-400">Erreur lors du chargement des données</p>
        <p className="text-sm text-gray-500">Vérifiez que DATABASE_URL est configuré</p>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Page Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Tableau de bord</h1>
          <p className="text-sm text-gray-400">Bienvenue, voici un aperçu de votre plateforme</p>
        </div>
        <Link
          href="/admin/analytics"
          className="flex items-center gap-2 rounded-lg bg-gradient-to-r from-purple-500 to-pink-500 px-4 py-2 text-sm font-medium text-white transition-opacity hover:opacity-90"
        >
          <BarChart3 className="h-4 w-4" />
          Voir les analytiques
        </Link>
      </div>

      {/* Stats Grid */}
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        {dashboardStats.map((stat) => (
          <div
            key={stat.name}
            className="rounded-xl border border-white/10 bg-gradient-to-br from-white/5 to-white/[0.02] p-5"
          >
            <div className="flex items-center justify-between">
              <div className={`flex h-10 w-10 items-center justify-center rounded-lg bg-gradient-to-br ${stat.color}`}>
                <stat.icon className="h-5 w-5 text-white" />
              </div>
              <span
                className={`flex items-center gap-1 text-xs font-medium ${
                  stat.trend === "up" ? "text-green-400" : stat.trend === "down" ? "text-red-400" : "text-gray-400"
                }`}
              >
                {stat.trend === "up" ? (
                  <TrendingUp className="h-3 w-3" />
                ) : stat.trend === "down" ? (
                  <TrendingDown className="h-3 w-3" />
                ) : null}
                {stat.change}
              </span>
            </div>
            <div className="mt-4">
              <p className="text-2xl font-bold text-white">{stat.value}</p>
              <p className="text-sm text-gray-400">{stat.name}</p>
            </div>
          </div>
        ))}
      </div>

      {/* Main Content Grid */}
      <div className="grid gap-6 lg:grid-cols-3">
        {/* Top Tracks */}
        <div className="lg:col-span-2 rounded-xl border border-white/10 bg-gradient-to-br from-white/5 to-white/[0.02]">
          <div className="flex items-center justify-between border-b border-white/10 p-4">
            <h2 className="font-semibold text-white">Titres les plus écoutés</h2>
            <Link
              href="/admin/tracks"
              className="flex items-center gap-1 text-sm text-purple-400 hover:text-purple-300"
            >
              Voir tout <ArrowUpRight className="h-4 w-4" />
            </Link>
          </div>
          <div className="divide-y divide-white/5">
            {topTracks.length > 0 ? (
              topTracks.map((track: any, index: number) => (
                <div key={track.id} className="flex items-center gap-4 p-4 hover:bg-white/5">
                  <span className="w-6 text-center text-sm font-medium text-gray-500">{index + 1}</span>
                  <div className="h-12 w-12 overflow-hidden rounded-lg">
                    <Image
                      src={track.image || "/placeholder.svg"}
                      alt={track.title}
                      width={48}
                      height={48}
                      className="h-full w-full object-cover"
                    />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="truncate font-medium text-white">{track.title}</p>
                    <p className="truncate text-sm text-gray-400">{track.artist}</p>
                  </div>
                  <div className="flex items-center gap-4">
                    <span className="text-sm text-gray-400">{formatNumber(track.plays)}</span>
                    <button className="text-gray-500 hover:text-white">
                      <MoreHorizontal className="h-5 w-5" />
                    </button>
                  </div>
                </div>
              ))
            ) : (
              <div className="p-8 text-center text-gray-400">Aucun titre disponible</div>
            )}
          </div>
        </div>

        {/* Recent Activity */}
        <div className="rounded-xl border border-white/10 bg-gradient-to-br from-white/5 to-white/[0.02]">
          <div className="flex items-center justify-between border-b border-white/10 p-4">
            <h2 className="font-semibold text-white">Activité récente</h2>
            <button className="text-gray-500 hover:text-white">
              <Eye className="h-5 w-5" />
            </button>
          </div>
          <div className="divide-y divide-white/5">
            {recentActivity.length > 0 ? (
              recentActivity.map((activity: any, index: number) => (
                <div key={index} className="p-4">
                  <p className="text-sm text-white">{activity.message}</p>
                  <p className="mt-1 text-xs text-gray-500">{activity.time}</p>
                </div>
              ))
            ) : (
              <div className="p-8 text-center text-gray-400">Aucune activité récente</div>
            )}
          </div>
        </div>
      </div>

      {/* Recent Users */}
      <div className="rounded-xl border border-white/10 bg-gradient-to-br from-white/5 to-white/[0.02]">
        <div className="flex items-center justify-between border-b border-white/10 p-4">
          <h2 className="font-semibold text-white">Utilisateurs récents</h2>
          <Link href="/admin/users" className="flex items-center gap-1 text-sm text-purple-400 hover:text-purple-300">
            Voir tout <ArrowUpRight className="h-4 w-4" />
          </Link>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-white/10 text-left">
                <th className="p-4 text-xs font-medium uppercase text-gray-500">Utilisateur</th>
                <th className="p-4 text-xs font-medium uppercase text-gray-500">Email</th>
                <th className="p-4 text-xs font-medium uppercase text-gray-500">Statut</th>
                <th className="p-4 text-xs font-medium uppercase text-gray-500">Inscrit</th>
                <th className="p-4 text-xs font-medium uppercase text-gray-500">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-white/5">
              {recentUsers.length > 0 ? (
                recentUsers.map((user: any) => (
                  <tr key={user.id} className="hover:bg-white/5">
                    <td className="p-4">
                      <div className="flex items-center gap-3">
                        <div className="h-8 w-8 overflow-hidden rounded-full">
                          <Image
                            src={user.avatar || "/placeholder.svg"}
                            alt={user.name}
                            width={32}
                            height={32}
                            className="h-full w-full object-cover"
                          />
                        </div>
                        <span className="font-medium text-white">{user.name}</span>
                      </div>
                    </td>
                    <td className="p-4 text-sm text-gray-400">{user.email}</td>
                    <td className="p-4">
                      <span
                        className={`inline-flex rounded-full px-2 py-1 text-xs font-medium ${
                          user.status === "Premium"
                            ? "bg-purple-500/20 text-purple-400"
                            : "bg-gray-500/20 text-gray-400"
                        }`}
                      >
                        {user.status}
                      </span>
                    </td>
                    <td className="p-4 text-sm text-gray-400">{user.date}</td>
                    <td className="p-4">
                      <button className="text-gray-500 hover:text-white">
                        <MoreHorizontal className="h-5 w-5" />
                      </button>
                    </td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={5} className="p-8 text-center text-gray-400">
                    Aucun utilisateur récent
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  )
}

function BarChart3(props: React.SVGProps<SVGSVGElement>) {
  return (
    <svg
      {...props}
      xmlns="http://www.w3.org/2000/svg"
      width="24"
      height="24"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="M3 3v18h18" />
      <path d="M18 17V9" />
      <path d="M13 17V5" />
      <path d="M8 17v-3" />
    </svg>
  )
}
