"use client"

import { useState } from "react"
import { Search, Download, RefreshCw, AlertCircle, Info, AlertTriangle, CheckCircle, Loader2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Badge } from "@/components/ui/badge"
import useSWR, { mutate } from "swr"

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

export default function AdminLogsPage() {
  const { data, isLoading, error } = useSWR("/api/admin/logs", fetcher)
  const [searchQuery, setSearchQuery] = useState("")
  const [levelFilter, setLevelFilter] = useState("all")
  const [sourceFilter, setSourceFilter] = useState("all")

  const logs = data?.logs || []

  const filteredLogs = logs.filter((log: any) => {
    const matchesSearch =
      log.action?.toLowerCase().includes(searchQuery.toLowerCase()) ||
      log.details?.toLowerCase().includes(searchQuery.toLowerCase())
    const matchesLevel = levelFilter === "all" || log.level === levelFilter
    return matchesSearch && matchesLevel
  })

  const sources = [...new Set(logs.map((l: any) => l.source || "system"))]

  const getLevelIcon = (level: string) => {
    switch (level) {
      case "error":
        return <AlertCircle className="w-4 h-4 text-red-400" />
      case "warning":
        return <AlertTriangle className="w-4 h-4 text-yellow-400" />
      case "success":
        return <CheckCircle className="w-4 h-4 text-green-400" />
      default:
        return <Info className="w-4 h-4 text-blue-400" />
    }
  }

  const getLevelBadge = (level: string) => {
    switch (level) {
      case "error":
        return <Badge className="bg-red-500/20 text-red-400 border-0">ERROR</Badge>
      case "warning":
        return <Badge className="bg-yellow-500/20 text-yellow-400 border-0">WARN</Badge>
      case "success":
        return <Badge className="bg-green-500/20 text-green-400 border-0">SUCCESS</Badge>
      default:
        return <Badge className="bg-blue-500/20 text-blue-400 border-0">INFO</Badge>
    }
  }

  const handleRefresh = () => {
    mutate("/api/admin/logs")
  }

  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) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <p className="text-red-400">Erreur lors du chargement des données</p>
      </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">Logs système</h1>
          <p className="text-zinc-400 text-sm">Consultez les logs de la plateforme</p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" className="border-zinc-700 text-zinc-300 bg-transparent" onClick={handleRefresh}>
            <RefreshCw className="w-4 h-4 mr-2" />
            Actualiser
          </Button>
          <Button variant="outline" className="border-zinc-700 text-zinc-300 bg-transparent">
            <Download className="w-4 h-4 mr-2" />
            Exporter
          </Button>
        </div>
      </div>

      {/* Filters */}
      <div className="flex flex-col gap-4 sm:flex-row">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-zinc-400" />
          <Input
            placeholder="Rechercher dans les logs..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-10 bg-zinc-800/50 border-zinc-700 text-white font-mono text-sm"
          />
        </div>
        <Select value={levelFilter} onValueChange={setLevelFilter}>
          <SelectTrigger className="w-full sm:w-32 bg-zinc-800/50 border-zinc-700 text-white">
            <SelectValue placeholder="Niveau" />
          </SelectTrigger>
          <SelectContent className="bg-zinc-800 border-zinc-700">
            <SelectItem value="all">Tous</SelectItem>
            <SelectItem value="error">Erreur</SelectItem>
            <SelectItem value="warning">Warning</SelectItem>
            <SelectItem value="info">Info</SelectItem>
            <SelectItem value="success">Succès</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* Logs */}
      <div className="bg-zinc-900/50 rounded-xl border border-zinc-700/50 overflow-hidden">
        <div className="overflow-x-auto">
          <div className="min-w-[600px]">
            {/* Header */}
            <div className="grid grid-cols-[180px_80px_180px_1fr] gap-4 p-3 border-b border-zinc-700/50 bg-zinc-800/30">
              <span className="text-xs font-medium text-zinc-400">TIMESTAMP</span>
              <span className="text-xs font-medium text-zinc-400">LEVEL</span>
              <span className="text-xs font-medium text-zinc-400">USER</span>
              <span className="text-xs font-medium text-zinc-400">MESSAGE</span>
            </div>

            {/* Log entries */}
            <div className="divide-y divide-zinc-800">
              {filteredLogs.length > 0 ? (
                filteredLogs.map((log: any) => (
                  <div
                    key={log.id}
                    className="grid grid-cols-[180px_80px_180px_1fr] gap-4 p-3 hover:bg-zinc-800/30 transition-colors items-center"
                  >
                    <span className="text-xs text-zinc-400 font-mono">{log.timestamp}</span>
                    <div>{getLevelBadge(log.level)}</div>
                    <span className="text-xs text-zinc-300 font-mono">{log.user}</span>
                    <div className="flex items-center gap-2">
                      {getLevelIcon(log.level)}
                      <span className="text-sm text-white font-mono truncate">{log.details || log.action}</span>
                    </div>
                  </div>
                ))
              ) : (
                <div className="p-8 text-center text-zinc-400">Aucun log disponible</div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Stats */}
      <div className="grid gap-4 sm:grid-cols-4">
        <div className="bg-zinc-800/30 rounded-lg border border-zinc-700/50 p-4 text-center">
          <p className="text-2xl font-bold text-red-400">{logs.filter((l: any) => l.level === "error").length}</p>
          <p className="text-sm text-zinc-400">Erreurs</p>
        </div>
        <div className="bg-zinc-800/30 rounded-lg border border-zinc-700/50 p-4 text-center">
          <p className="text-2xl font-bold text-yellow-400">{logs.filter((l: any) => l.level === "warning").length}</p>
          <p className="text-sm text-zinc-400">Warnings</p>
        </div>
        <div className="bg-zinc-800/30 rounded-lg border border-zinc-700/50 p-4 text-center">
          <p className="text-2xl font-bold text-blue-400">{logs.filter((l: any) => l.level === "info").length}</p>
          <p className="text-sm text-zinc-400">Info</p>
        </div>
        <div className="bg-zinc-800/30 rounded-lg border border-zinc-700/50 p-4 text-center">
          <p className="text-2xl font-bold text-green-400">{logs.filter((l: any) => l.level === "success").length}</p>
          <p className="text-sm text-zinc-400">Succès</p>
        </div>
      </div>
    </div>
  )
}
