"use client"

import { useState } from "react"
import useSWR from "swr"
import {
  Key,
  Plus,
  Copy,
  Eye,
  EyeOff,
  Trash2,
  MoreHorizontal,
  Building2,
  TrendingUp,
  DollarSign,
  Music,
  Phone,
  Settings,
  RefreshCw,
} 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 { Textarea } from "@/components/ui/textarea"
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"
import { useToast } from "@/hooks/use-toast"
import Link from "next/link"

const getAuthToken = () => {
  if (typeof window !== "undefined") {
    return localStorage.getItem("auth_token")
  }
  return null
}

const fetcher = async (url: string) => {
  const token = getAuthToken()
  const res = await fetch(url, {
    headers: token ? { Authorization: `Bearer ${token}` } : {},
  })
  if (!res.ok) {
    const error = await res.json()
    throw new Error(error.error || "Failed to fetch")
  }
  return res.json()
}

export default function RingtoneApiPage() {
  const { toast } = useToast()
  const { data: apiKeysData, mutate, isLoading, error: apiKeysError } = useSWR("/api/admin/ringtone-api", fetcher)
  const { data: statsData } = useSWR("/api/admin/ringtone-api/stats", fetcher)

  const apiKeys = apiKeysData?.data || []
  const stats = statsData?.data || { totalKeys: 0, totalDownloads: 0, totalRevenue: 0, enabledTracks: 0 }

  const [showCreateDialog, setShowCreateDialog] = useState(false)
  const [showDeleteDialog, setShowDeleteDialog] = useState<string | null>(null)
  const [showEditDialog, setShowEditDialog] = useState<any | null>(null)
  const [visibleKeys, setVisibleKeys] = useState<string[]>([])
  const [newKeyData, setNewKeyData] = useState({
    name: "",
    company: "",
    rateLimit: 1000,
    expiresIn: "1year",
    notes: "",
  })
  const [createdKey, setCreatedKey] = useState<{ apiKey: string; apiSecret: string } | null>(null)
  const [isCreating, setIsCreating] = useState(false)
  const [isDeleting, setIsDeleting] = useState(false)
  const [isSaving, setIsSaving] = useState(false)

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

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text)
    toast({ title: "Copié dans le presse-papier!" })
  }

  const createNewKey = async () => {
    if (!newKeyData.name || !newKeyData.company) {
      toast({ title: "Veuillez remplir tous les champs requis", variant: "destructive" })
      return
    }

    setIsCreating(true)
    const token = getAuthToken()

    try {
      const response = await fetch("/api/admin/ringtone-api", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          ...(token ? { Authorization: `Bearer ${token}` } : {}),
        },
        body: JSON.stringify(newKeyData),
      })

      const result = await response.json()

      if (response.ok && result.success) {
        setCreatedKey(result.data)
        mutate()
        toast({ title: "Clé API créée avec succès!" })
      } else {
        toast({ title: result.error || "Erreur lors de la création", variant: "destructive" })
      }
    } catch (error) {
      toast({ title: "Erreur réseau", variant: "destructive" })
    } finally {
      setIsCreating(false)
    }
  }

  const deleteApiKey = async () => {
    if (!showDeleteDialog) return

    setIsDeleting(true)
    const token = getAuthToken()

    try {
      const response = await fetch(`/api/admin/ringtone-api/${showDeleteDialog}`, {
        method: "DELETE",
        headers: token ? { Authorization: `Bearer ${token}` } : {},
      })

      if (response.ok) {
        mutate()
        setShowDeleteDialog(null)
        toast({ title: "Clé API supprimée" })
      } else {
        const result = await response.json()
        toast({ title: result.error || "Erreur lors de la suppression", variant: "destructive" })
      }
    } catch (error) {
      toast({ title: "Erreur réseau", variant: "destructive" })
    } finally {
      setIsDeleting(false)
    }
  }

  const updateApiKey = async () => {
    if (!showEditDialog) return

    setIsSaving(true)
    const token = getAuthToken()

    try {
      const response = await fetch(`/api/admin/ringtone-api/${showEditDialog.id}`, {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
          ...(token ? { Authorization: `Bearer ${token}` } : {}),
        },
        body: JSON.stringify({
          status: showEditDialog.status,
          rate_limit: showEditDialog.rate_limit,
          notes: showEditDialog.notes,
          callback_url: showEditDialog.callback_url,
        }),
      })

      if (response.ok) {
        mutate()
        setShowEditDialog(null)
        toast({ title: "Clé API mise à jour" })
      } else {
        const result = await response.json()
        toast({ title: result.error || "Erreur lors de la mise à jour", variant: "destructive" })
      }
    } catch (error) {
      toast({ title: "Erreur réseau", variant: "destructive" })
    } finally {
      setIsSaving(false)
    }
  }

  const closeCreateDialog = () => {
    setShowCreateDialog(false)
    setCreatedKey(null)
    setNewKeyData({
      name: "",
      company: "",
      rateLimit: 1000,
      expiresIn: "1year",
      notes: "",
    })
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
        <div>
          <h1 className="text-2xl font-bold">API Sonneries RBT - Opérateurs Télécoms</h1>
          <p className="text-muted-foreground">
            Gérez l'accès API externe pour les opérateurs mobiles utilisant les sonneries de la plateforme
          </p>
        </div>
        <div className="flex gap-2">
          <Link href="/admin/ringtone-api/downloads">
            <Button variant="outline">
              <Phone className="mr-2 h-4 w-4" />
              Téléchargements RBT
            </Button>
          </Link>
          <Button onClick={() => setShowCreateDialog(true)}>
            <Plus className="mr-2 h-4 w-4" />
            Nouvelle Clé API Opérateur
          </Button>
        </div>
      </div>

      {/* Stats Cards */}
      <div className="grid gap-4 md:grid-cols-4">
        <div className="rounded-lg border bg-card p-6">
          <div className="flex items-center gap-3">
            <div className="rounded-full bg-primary/10 p-2">
              <Building2 className="h-5 w-5 text-primary" />
            </div>
            <div>
              <p className="text-2xl font-bold">{stats.totalKeys || apiKeys.length}</p>
              <p className="text-sm text-muted-foreground">Opérateurs Actifs</p>
            </div>
          </div>
        </div>
        <div className="rounded-lg border bg-card p-6">
          <div className="flex items-center gap-3">
            <div className="rounded-full bg-green-500/10 p-2">
              <TrendingUp className="h-5 w-5 text-green-500" />
            </div>
            <div>
              <p className="text-2xl font-bold">{stats.totalDownloads || 0}</p>
              <p className="text-sm text-muted-foreground">Total Téléchargements</p>
            </div>
          </div>
        </div>
        <div className="rounded-lg border bg-card p-6">
          <div className="flex items-center gap-3">
            <div className="rounded-full bg-yellow-500/10 p-2">
              <DollarSign className="h-5 w-5 text-yellow-500" />
            </div>
            <div>
              <p className="text-2xl font-bold">${stats.totalRevenue || 0}</p>
              <p className="text-sm text-muted-foreground">Revenus Total</p>
            </div>
          </div>
        </div>
        <div className="rounded-lg border bg-card p-6">
          <div className="flex items-center gap-3">
            <div className="rounded-full bg-purple-500/10 p-2">
              <Music className="h-5 w-5 text-purple-500" />
            </div>
            <div>
              <p className="text-2xl font-bold">{stats.enabledTracks || 0}</p>
              <p className="text-sm text-muted-foreground">Sonneries Disponibles</p>
            </div>
          </div>
        </div>
      </div>

      {/* API Keys List */}
      <div className="rounded-lg border bg-card">
        <div className="border-b p-4">
          <h2 className="font-semibold flex items-center gap-2">
            <Key className="h-4 w-4" />
            Clés API Opérateurs ({apiKeys.length})
          </h2>
        </div>

        {isLoading ? (
          <div className="p-8 text-center text-muted-foreground">Chargement...</div>
        ) : apiKeysError ? (
          <div className="p-8 text-center text-red-500">Erreur: {apiKeysError.message}</div>
        ) : apiKeys.length === 0 ? (
          <div className="p-8 text-center text-muted-foreground">
            <Key className="mx-auto h-12 w-12 opacity-50 mb-3" />
            <p>Aucune clé API créée</p>
            <p className="text-sm">Créez votre première clé API pour les opérateurs</p>
          </div>
        ) : (
          <div className="divide-y">
            {apiKeys.map((key: any) => (
              <div key={key.id} className="p-4 flex items-center justify-between">
                <div className="flex-1">
                  <div className="flex items-center gap-2">
                    <span className="font-medium">{key.name}</span>
                    <Badge variant={key.status === "active" ? "default" : "secondary"}>{key.status}</Badge>
                    {key.company && <span className="text-sm text-muted-foreground">• {key.company}</span>}
                  </div>
                  <div className="flex items-center gap-2 mt-1">
                    <code className="text-xs bg-muted px-2 py-1 rounded font-mono">
                      {visibleKeys.includes(key.id) ? key.api_key : key.api_key?.slice(0, 20) + "..."}
                    </code>
                    <Button variant="ghost" size="icon" className="h-6 w-6" onClick={() => toggleKeyVisibility(key.id)}>
                      {visibleKeys.includes(key.id) ? <EyeOff className="h-3 w-3" /> : <Eye className="h-3 w-3" />}
                    </Button>
                    <Button
                      variant="ghost"
                      size="icon"
                      className="h-6 w-6"
                      onClick={() => copyToClipboard(key.api_key)}
                    >
                      <Copy className="h-3 w-3" />
                    </Button>
                  </div>
                  <div className="flex gap-4 mt-2 text-xs text-muted-foreground">
                    <span>Limite: {key.rate_limit}/jour</span>
                    <span>Requêtes: {key.requests_count || 0}</span>
                    {key.expires_at && <span>Expire: {new Date(key.expires_at).toLocaleDateString()}</span>}
                  </div>
                </div>
                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <Button variant="ghost" size="icon">
                      <MoreHorizontal className="h-4 w-4" />
                    </Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent align="end">
                    <DropdownMenuItem onClick={() => setShowEditDialog(key)}>
                      <Settings className="mr-2 h-4 w-4" />
                      Modifier
                    </DropdownMenuItem>
                    <DropdownMenuItem onClick={() => copyToClipboard(key.api_key)}>
                      <Copy className="mr-2 h-4 w-4" />
                      Copier la clé
                    </DropdownMenuItem>
                    <DropdownMenuItem className="text-red-500" onClick={() => setShowDeleteDialog(key.id)}>
                      <Trash2 className="mr-2 h-4 w-4" />
                      Supprimer
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* API Documentation */}
      <div className="rounded-lg border bg-card p-6">
        <h2 className="font-semibold mb-4">Documentation API & Fonctionnalités</h2>
        <p className="text-muted-foreground mb-6">
          Intégrez les sonneries AfricanMusic dans votre plateforme d'opérateur mobile avec notre API REST sécurisée.
        </p>

        <div className="grid md:grid-cols-3 gap-4 mb-6">
          <div className="flex items-start gap-2">
            <span className="text-green-500">✓</span>
            <div>
              <p className="font-medium text-green-500">API REST sécurisée</p>
              <p className="text-sm text-muted-foreground">Token / API Key authentication</p>
            </div>
          </div>
          <div className="flex items-start gap-2">
            <span className="text-green-500">✓</span>
            <div>
              <p className="font-medium text-green-500">Catalogue exportable</p>
              <p className="text-sm text-muted-foreground">JSON, CSV, XML formats</p>
            </div>
          </div>
          <div className="flex items-start gap-2">
            <span className="text-green-500">✓</span>
            <div>
              <p className="font-medium text-green-500">Suivi par MSISDN</p>
              <p className="text-sm text-muted-foreground">Tracking par numéro mobile</p>
            </div>
          </div>
          <div className="flex items-start gap-2">
            <span className="text-green-500">✓</span>
            <div>
              <p className="font-medium text-green-500">Statistiques</p>
              <p className="text-sm text-muted-foreground">Par opérateur et période</p>
            </div>
          </div>
          <div className="flex items-start gap-2">
            <span className="text-green-500">✓</span>
            <div>
              <p className="font-medium text-green-500">Pricing dynamique</p>
              <p className="text-sm text-muted-foreground">Tarifs par opérateur</p>
            </div>
          </div>
          <div className="flex items-start gap-2">
            <span className="text-green-500">✓</span>
            <div>
              <p className="font-medium text-green-500">Confirmation livraison</p>
              <p className="text-sm text-muted-foreground">Webhook & callbacks</p>
            </div>
          </div>
        </div>

        <div className="grid md:grid-cols-2 gap-4 mb-6">
          <div>
            <p className="text-green-500 font-mono text-sm">GET /api/v1/ringtones</p>
            <p className="text-sm text-muted-foreground">Rechercher et parcourir les sonneries disponibles</p>
          </div>
          <div>
            <p className="text-purple-500 font-mono text-sm">POST /api/v1/ringtones/:id</p>
            <p className="text-sm text-muted-foreground">Enregistrer achat avec MSISDN et obtenir l'URL</p>
          </div>
          <div>
            <p className="text-green-500 font-mono text-sm">GET /api/v1/ringtones/:id/download</p>
            <p className="text-sm text-muted-foreground">Télécharger le fichier sonnerie (token requis)</p>
          </div>
          <div>
            <p className="text-purple-500 font-mono text-sm">POST /api/v1/ringtones/:id/confirm</p>
            <p className="text-sm text-muted-foreground">Confirmer la livraison au client</p>
          </div>
        </div>

        <div className="bg-muted/50 rounded p-4 font-mono text-sm space-y-2">
          <p className="text-green-400">
            curl -H "x-api-key: YOUR_API_KEY" https://africanmusic.online/api/v1/ringtones
          </p>
          <p className="text-purple-400">
            curl -X POST -H "x-api-key: YOUR_API_KEY" -H "Content-Type: application/json" -d '
            {`{"msisdn": "+22370123456", "transaction_id": "TXN123"}`}'
            https://africanmusic.online/api/v1/ringtones/TRACK_ID
          </p>
        </div>
      </div>

      {/* Create Dialog */}
      <Dialog open={showCreateDialog} onOpenChange={closeCreateDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Créer une Nouvelle Clé API Opérateur</DialogTitle>
            <DialogDescription>
              Générez des identifiants API pour un opérateur mobile pour accéder aux sonneries
            </DialogDescription>
          </DialogHeader>

          {createdKey ? (
            <div className="space-y-4">
              <div className="rounded-lg bg-green-500/10 border border-green-500/20 p-4">
                <p className="text-green-500 font-medium mb-2">Clé API créée avec succès!</p>
                <p className="text-sm text-muted-foreground mb-4">
                  Copiez ces informations maintenant. Le secret ne sera plus affiché.
                </p>
              </div>

              <div className="space-y-3">
                <div>
                  <Label>API Key</Label>
                  <div className="flex gap-2">
                    <Input value={createdKey.apiKey} readOnly className="font-mono text-xs" />
                    <Button variant="outline" size="icon" onClick={() => copyToClipboard(createdKey.apiKey)}>
                      <Copy className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
                <div>
                  <Label>API Secret</Label>
                  <div className="flex gap-2">
                    <Input value={createdKey.apiSecret} readOnly className="font-mono text-xs" />
                    <Button variant="outline" size="icon" onClick={() => copyToClipboard(createdKey.apiSecret)}>
                      <Copy className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              </div>

              <DialogFooter>
                <Button onClick={closeCreateDialog}>Fermer</Button>
              </DialogFooter>
            </div>
          ) : (
            <>
              <div className="space-y-4">
                <div className="space-y-2">
                  <Label>Nom de l'API</Label>
                  <Input
                    value={newKeyData.name}
                    onChange={(e) => setNewKeyData({ ...newKeyData, name: e.target.value })}
                    placeholder="Production API"
                  />
                </div>
                <div className="space-y-2">
                  <Label>Nom de l'Entreprise</Label>
                  <Input
                    value={newKeyData.company}
                    onChange={(e) => setNewKeyData({ ...newKeyData, company: e.target.value })}
                    placeholder="Orange Mali"
                  />
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label>Limite (requêtes/jour)</Label>
                    <Input
                      type="number"
                      value={newKeyData.rateLimit}
                      onChange={(e) =>
                        setNewKeyData({ ...newKeyData, rateLimit: Number.parseInt(e.target.value) || 1000 })
                      }
                    />
                  </div>
                  <div className="space-y-2">
                    <Label>Expire dans</Label>
                    <Select
                      value={newKeyData.expiresIn}
                      onValueChange={(value) => setNewKeyData({ ...newKeyData, expiresIn: value })}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="1month">1 Mois</SelectItem>
                        <SelectItem value="6months">6 Mois</SelectItem>
                        <SelectItem value="1year">1 An</SelectItem>
                        <SelectItem value="never">Jamais</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
                <div className="space-y-2">
                  <Label>Notes (Optionnel)</Label>
                  <Textarea
                    value={newKeyData.notes}
                    onChange={(e) => setNewKeyData({ ...newKeyData, notes: e.target.value })}
                    placeholder="Notes additionnelles sur cette clé API..."
                    rows={3}
                  />
                </div>
              </div>

              <DialogFooter>
                <Button variant="outline" onClick={closeCreateDialog}>
                  Annuler
                </Button>
                <Button onClick={createNewKey} disabled={isCreating}>
                  {isCreating ? (
                    <>
                      <RefreshCw className="mr-2 h-4 w-4 animate-spin" />
                      Création...
                    </>
                  ) : (
                    "Générer la Clé API"
                  )}
                </Button>
              </DialogFooter>
            </>
          )}
        </DialogContent>
      </Dialog>

      {/* Edit Dialog */}
      <Dialog open={!!showEditDialog} onOpenChange={() => setShowEditDialog(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Modifier la Clé API</DialogTitle>
            <DialogDescription>Mettre à jour les paramètres de la clé API</DialogDescription>
          </DialogHeader>

          {showEditDialog && (
            <div className="space-y-4">
              <div className="space-y-2">
                <Label>Statut</Label>
                <Select
                  value={showEditDialog.status}
                  onValueChange={(value) => setShowEditDialog({ ...showEditDialog, status: value })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="active">Actif</SelectItem>
                    <SelectItem value="inactive">Inactif</SelectItem>
                    <SelectItem value="suspended">Suspendu</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Limite (requêtes/jour)</Label>
                <Input
                  type="number"
                  value={showEditDialog.rate_limit}
                  onChange={(e) =>
                    setShowEditDialog({ ...showEditDialog, rate_limit: Number.parseInt(e.target.value) || 1000 })
                  }
                />
              </div>
              <div className="space-y-2">
                <Label>URL de Callback</Label>
                <Input
                  value={showEditDialog.callback_url || ""}
                  onChange={(e) => setShowEditDialog({ ...showEditDialog, callback_url: e.target.value })}
                  placeholder="https://operator.com/webhook"
                />
              </div>
              <div className="space-y-2">
                <Label>Notes</Label>
                <Textarea
                  value={showEditDialog.notes || ""}
                  onChange={(e) => setShowEditDialog({ ...showEditDialog, notes: e.target.value })}
                  rows={3}
                />
              </div>
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowEditDialog(null)}>
              Annuler
            </Button>
            <Button onClick={updateApiKey} disabled={isSaving}>
              {isSaving ? (
                <>
                  <RefreshCw className="mr-2 h-4 w-4 animate-spin" />
                  Sauvegarde...
                </>
              ) : (
                "Sauvegarder"
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete Dialog */}
      <Dialog open={!!showDeleteDialog} onOpenChange={() => setShowDeleteDialog(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Supprimer la Clé API</DialogTitle>
            <DialogDescription>
              Êtes-vous sûr de vouloir supprimer cette clé API? Cette action est irréversible.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDeleteDialog(null)}>
              Annuler
            </Button>
            <Button variant="destructive" onClick={deleteApiKey} disabled={isDeleting}>
              {isDeleting ? (
                <>
                  <RefreshCw className="mr-2 h-4 w-4 animate-spin" />
                  Suppression...
                </>
              ) : (
                "Supprimer"
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
