"use client"

import { useState } from "react"
import useSWR from "swr"
import { Activity, AlertCircle, CheckCircle, Clock, XCircle } from "lucide-react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Badge } from "@/components/ui/badge"
import { Loader2 } from "lucide-react"

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

export default function APIMonitoringPage() {
  const [period, setPeriod] = useState("24h")

  const { data: logsData, isLoading } = useSWR("/api/admin/ringtone-api/logs", fetcher, {
    refreshInterval: 30000,
  })
  const { data: statsData } = useSWR("/api/admin/ringtone-api/stats", fetcher, {
    refreshInterval: 60000,
  })

  const logs = logsData?.logs || []
  const stats = statsData || {}

  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">Monitoring API</h1>
          <p className="text-zinc-400 text-sm">Surveillance en temps réel de l'API Ringtones</p>
        </div>
        <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="1h">Dernière heure</SelectItem>
            <SelectItem value="24h">24 heures</SelectItem>
            <SelectItem value="7d">7 jours</SelectItem>
            <SelectItem value="30d">30 jours</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* Stats Cards */}
      <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 Requêtes</CardTitle>
            <Activity className="w-4 h-4 text-blue-400" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-white">{formatNumber(stats.totalRequests || 0)}</div>
            <p className="text-xs text-zinc-400 mt-1">Dernières 24h</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">Succès</CardTitle>
            <CheckCircle className="w-4 h-4 text-green-400" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-white">{formatNumber(stats.successfulRequests || 0)}</div>
            <p className="text-xs text-green-400 mt-1">
              {stats.totalRequests > 0
                ? `${((stats.successfulRequests / stats.totalRequests) * 100).toFixed(1)}% taux de succès`
                : "0% taux de succès"}
            </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">Erreurs</CardTitle>
            <XCircle className="w-4 h-4 text-red-400" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-white">{formatNumber(stats.errorRequests || 0)}</div>
            <p className="text-xs text-red-400 mt-1">
              {stats.totalRequests > 0
                ? `${((stats.errorRequests / stats.totalRequests) * 100).toFixed(1)}% taux d'erreur`
                : "0% taux d'erreur"}
            </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">Temps Moyen</CardTitle>
            <Clock className="w-4 h-4 text-purple-400" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-white">{stats.avgResponseTime || 0}ms</div>
            <p className="text-xs text-zinc-400 mt-1">Temps de réponse</p>
          </CardContent>
        </Card>
      </div>

      {/* Recent Logs */}
      <Card className="bg-zinc-800/30 border-zinc-700/50">
        <CardHeader>
          <CardTitle className="text-white">Requêtes Récentes</CardTitle>
          <CardDescription className="text-zinc-400">Logs d'activité de l'API en temps réel</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-2">
            {logs.length > 0 ? (
              logs.map((log: any) => (
                <div
                  key={log.id}
                  className="flex items-center justify-between p-3 bg-zinc-700/30 rounded-lg hover:bg-zinc-700/50 transition-colors"
                >
                  <div className="flex items-center gap-3 flex-1">
                    {log.status_code >= 200 && log.status_code < 300 ? (
                      <CheckCircle className="w-4 h-4 text-green-400 flex-shrink-0" />
                    ) : log.status_code >= 400 && log.status_code < 500 ? (
                      <AlertCircle className="w-4 h-4 text-yellow-400 flex-shrink-0" />
                    ) : (
                      <XCircle className="w-4 h-4 text-red-400 flex-shrink-0" />
                    )}
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium text-white truncate">
                        {log.method} {log.endpoint}
                      </p>
                      <p className="text-xs text-zinc-400">
                        Opérateur: {log.operator_name || "Inconnu"} • {log.response_time}ms
                      </p>
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    <Badge
                      variant={
                        log.status_code >= 200 && log.status_code < 300
                          ? "default"
                          : log.status_code >= 400
                            ? "destructive"
                            : "secondary"
                      }
                      className="flex-shrink-0"
                    >
                      {log.status_code}
                    </Badge>
                    <span className="text-xs text-zinc-500 whitespace-nowrap">
                      {new Date(log.created_at).toLocaleTimeString("fr-FR")}
                    </span>
                  </div>
                </div>
              ))
            ) : (
              <p className="text-center text-zinc-400 py-8">Aucune requête récente</p>
            )}
          </div>
        </CardContent>
      </Card>

      {/* Operator Stats */}
      {stats.operatorStats && stats.operatorStats.length > 0 && (
        <Card className="bg-zinc-800/30 border-zinc-700/50">
          <CardHeader>
            <CardTitle className="text-white">Statistiques par Opérateur</CardTitle>
            <CardDescription className="text-zinc-400">Utilisation de l'API par opérateur</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {stats.operatorStats.map((operator: any) => (
                <div
                  key={operator.operator_id}
                  className="flex items-center justify-between p-4 bg-zinc-700/30 rounded-lg"
                >
                  <div>
                    <p className="font-medium text-white">{operator.operator_name}</p>
                    <p className="text-sm text-zinc-400">{formatNumber(operator.total_requests)} requêtes</p>
                  </div>
                  <div className="text-right">
                    <p className="text-sm font-medium text-green-400">
                      {formatNumber(operator.total_downloads)} téléchargements
                    </p>
                    <p className="text-xs text-zinc-400">
                      {new Intl.NumberFormat("fr-FR").format(operator.total_revenue || 0)} FCFA
                    </p>
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  )
}
