"use client"

import { useState } from "react"
import useSWR from "swr"
import { Key, Plus, Copy, Eye, EyeOff, Trash2, MoreHorizontal, RefreshCw, AlertTriangle, Loader2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Label } from "@/components/ui/label"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"

interface ApiKey {
  id: string
  name: string
  key: string
  status: "active" | "inactive"
  requests: number
  lastUsed: string
  createdAt: string
  permissions: string[]
}

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

export default function AdminApiPage() {
  const { data: apiKeysData, error, mutate } = useSWR("/api/admin/api-keys", fetcher)
  const apiKeys: ApiKey[] = apiKeysData?.data || []

  const [showCreateDialog, setShowCreateDialog] = useState(false)
  const [showDeleteDialog, setShowDeleteDialog] = useState<string | null>(null)
  const [visibleKeys, setVisibleKeys] = useState<string[]>([])
  const [newKey, setNewKey] = useState<string | null>(null)

  const toggleKeyVisibility = (id: string) => {
    setVisibleKeys((prev) => (prev.includes(id) ? prev.filter((k) => k !== id) : [...prev, id]))
  }

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text)
  }

  const formatNumber = (num: number) => {
    if (num >= 1000) return `${(num / 1000).toFixed(1)}K`
    return num.toString()
  }

  const createNewKey = async () => {
    const response = await fetch("/api/admin/api-keys", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        name: "New API Key",
        permissions: ["read"],
      }),
    })

    if (response.ok) {
      const result = await response.json()
      setNewKey(result.data.key)
      mutate()
    }
  }

  const handleDeleteKey = async (keyId: string) => {
    const response = await fetch(`/api/admin/api-keys/${keyId}`, {
      method: "DELETE",
    })

    if (response.ok) {
      mutate()
      setShowDeleteDialog(null)
    }
  }

  if (error) return <div className="text-red-400 p-4">Error loading API keys</div>
  if (!apiKeys)
    return (
      <div className="flex items-center justify-center p-8">
        <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">Cles API</h1>
          <p className="text-zinc-400 text-sm">Gerez vos cles d'acces a l'API</p>
        </div>
        <Button
          onClick={() => {
            setShowCreateDialog(true)
            setNewKey(null)
          }}
          className="bg-purple-600 hover:bg-purple-700"
        >
          <Plus className="w-4 h-4 mr-2" />
          Nouvelle cle
        </Button>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-4">
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg bg-purple-500/20">
              <Key className="w-5 h-5 text-purple-400" />
            </div>
            <div>
              <p className="text-xl font-bold text-white">
                {apiKeys.filter((k: ApiKey) => k.status === "active").length}
              </p>
              <p className="text-zinc-400 text-sm">Cles actives</p>
            </div>
          </div>
        </div>
        <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-4">
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg bg-green-500/20">
              <RefreshCw className="w-5 h-5 text-green-400" />
            </div>
            <div>
              <p className="text-xl font-bold text-white">
                {formatNumber(apiKeys.reduce((acc: number, k: ApiKey) => acc + k.requests, 0))}
              </p>
              <p className="text-zinc-400 text-sm">Requetes totales</p>
            </div>
          </div>
        </div>
      </div>

      {/* API Keys List */}
      <div className="space-y-4">
        {apiKeys.map((apiKey) => (
          <div key={apiKey.id} className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-4">
            <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
              <div className="flex-1">
                <div className="flex items-center gap-3 mb-2">
                  <h3 className="font-semibold text-white">{apiKey.name}</h3>
                  <Badge
                    className={
                      apiKey.status === "active"
                        ? "bg-green-500/20 text-green-400 border-0"
                        : "bg-zinc-500/20 text-zinc-400 border-0"
                    }
                  >
                    {apiKey.status === "active" ? "Actif" : "Inactif"}
                  </Badge>
                </div>
                <div className="flex items-center gap-2 mb-2">
                  <code className="text-sm bg-zinc-900 px-3 py-1 rounded text-zinc-300 font-mono">
                    {visibleKeys.includes(apiKey.id) ? apiKey.key : apiKey.key.replace(/./g, "•").slice(0, 20) + "..."}
                  </code>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-8 w-8 text-zinc-400"
                    onClick={() => toggleKeyVisibility(apiKey.id)}
                  >
                    {visibleKeys.includes(apiKey.id) ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                  </Button>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-8 w-8 text-zinc-400"
                    onClick={() => copyToClipboard(apiKey.key)}
                  >
                    <Copy className="w-4 h-4" />
                  </Button>
                </div>
                <div className="flex flex-wrap gap-4 text-sm text-zinc-400">
                  <span>Derniere utilisation: {apiKey.lastUsed}</span>
                  <span>{formatNumber(apiKey.requests)} requetes</span>
                  <span>Creee le {apiKey.createdAt}</span>
                </div>
              </div>
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button variant="ghost" size="icon" className="text-zinc-400">
                    <MoreHorizontal className="w-5 h-5" />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end" className="bg-zinc-800 border-zinc-700">
                  <DropdownMenuItem className="text-zinc-300">Regenerer</DropdownMenuItem>
                  <DropdownMenuItem className="text-zinc-300">Modifier les permissions</DropdownMenuItem>
                  <DropdownMenuItem className="text-red-400" onClick={() => setShowDeleteDialog(apiKey.id)}>
                    <Trash2 className="w-4 h-4 mr-2" /> Supprimer
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            </div>
          </div>
        ))}
      </div>

      {/* Create Dialog */}
      <Dialog open={showCreateDialog} onOpenChange={setShowCreateDialog}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
          <DialogHeader>
            <DialogTitle>Nouvelle cle API</DialogTitle>
            <DialogDescription className="text-zinc-400">Creer une nouvelle cle d'acces a l'API</DialogDescription>
          </DialogHeader>
          <div className="py-4 space-y-4">
            {!newKey ? (
              <>
                <div className="space-y-2">
                  <Label>Nom</Label>
                  <Input className="bg-zinc-800 border-zinc-700" placeholder="Mon application" />
                </div>
                <div className="space-y-2">
                  <Label>Permissions</Label>
                  <Select>
                    <SelectTrigger className="bg-zinc-800 border-zinc-700">
                      <SelectValue placeholder="Selectionner" />
                    </SelectTrigger>
                    <SelectContent className="bg-zinc-800 border-zinc-700">
                      <SelectItem value="read">Lecture seule</SelectItem>
                      <SelectItem value="read_write">Lecture et ecriture</SelectItem>
                      <SelectItem value="full">Acces complet</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </>
            ) : (
              <div className="space-y-4">
                <div className="bg-yellow-500/10 border border-yellow-500/30 rounded-lg p-4">
                  <div className="flex items-start gap-2">
                    <AlertTriangle className="w-5 h-5 text-yellow-400 mt-0.5" />
                    <p className="text-yellow-300 text-sm">
                      Copiez cette cle maintenant. Elle ne sera plus visible apres.
                    </p>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <code className="flex-1 text-sm bg-zinc-800 px-3 py-2 rounded text-green-400 font-mono break-all">
                    {newKey}
                  </code>
                  <Button variant="ghost" size="icon" onClick={() => copyToClipboard(newKey)}>
                    <Copy className="w-4 h-4" />
                  </Button>
                </div>
              </div>
            )}
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowCreateDialog(false)}>
              {newKey ? "Fermer" : "Annuler"}
            </Button>
            {!newKey && (
              <Button className="bg-purple-600 hover:bg-purple-700" onClick={createNewKey}>
                Creer
              </Button>
            )}
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete Dialog */}
      <Dialog open={!!showDeleteDialog} onOpenChange={() => setShowDeleteDialog(null)}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
          <DialogHeader>
            <DialogTitle className="text-red-400">Supprimer la cle API</DialogTitle>
            <DialogDescription className="text-zinc-400">
              Cette action est irreversible. Toutes les applications utilisant cette cle cesseront de fonctionner.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowDeleteDialog(null)}>
              Annuler
            </Button>
            <Button
              className="bg-red-600 hover:bg-red-700"
              onClick={() => showDeleteDialog && handleDeleteKey(showDeleteDialog)}
            >
              Supprimer
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
