"use client"

import { useState } from "react"
import useSWR from "swr"
import {
  Database,
  Download,
  Upload,
  Clock,
  CheckCircle,
  AlertTriangle,
  Trash2,
  RefreshCw,
  HardDrive,
  Loader2,
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Progress } from "@/components/ui/progress"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Label } from "@/components/ui/label"
import { useToast } from "@/hooks/use-toast"

const fetcher = (url: string) => {
  const token = typeof window !== "undefined" ? localStorage.getItem("auth_token") : null
  return fetch(url, {
    headers: token ? { Authorization: `Bearer ${token}` } : {},
  }).then((res) => res.json())
}

export default function AdminBackupsPage() {
  const { toast } = useToast()
  const { data, error, isLoading, mutate } = useSWR("/api/admin/backups", fetcher)
  const backups = data?.backups || []
  const stats = data?.stats || { total: 0, lastBackup: null, totalSize: "0 GB", autoTime: "03:00" }

  const [showCreateDialog, setShowCreateDialog] = useState(false)
  const [showRestoreDialog, setShowRestoreDialog] = useState(false)
  const [isBackingUp, setIsBackingUp] = useState(false)
  const [backupProgress, setBackupProgress] = useState(0)
  const [selectedBackup, setSelectedBackup] = useState("")

  const getAuthHeaders = () => {
    const token = typeof window !== "undefined" ? localStorage.getItem("auth_token") : null
    return {
      "Content-Type": "application/json",
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
    }
  }

  const startBackup = async () => {
    setIsBackingUp(true)
    setBackupProgress(0)

    // Simulate backup progress
    const interval = setInterval(() => {
      setBackupProgress((prev) => {
        if (prev >= 100) {
          clearInterval(interval)
          return 100
        }
        return prev + 10
      })
    }, 500)

    try {
      const token = typeof window !== "undefined" ? localStorage.getItem("auth_token") : null
      const res = await fetch("/api/admin/backups", {
        method: "POST",
        headers: token ? { Authorization: `Bearer ${token}` } : {},
      })
      if (res.ok) {
        clearInterval(interval)
        setBackupProgress(100)
        setTimeout(() => {
          setIsBackingUp(false)
          toast({ title: "Sauvegarde créée avec succès" })
          mutate()
        }, 500)
      } else {
        throw new Error("Backup failed")
      }
    } catch (e) {
      clearInterval(interval)
      setIsBackingUp(false)
      toast({ title: "Erreur lors de la sauvegarde", variant: "destructive" })
    }
  }

  const handleRestore = async () => {
    if (!selectedBackup) return
    try {
      const token = typeof window !== "undefined" ? localStorage.getItem("auth_token") : null
      const res = await fetch(`/api/admin/backups/${selectedBackup}/restore`, {
        method: "POST",
        headers: token ? { Authorization: `Bearer ${token}` } : {},
      })
      if (res.ok) {
        toast({ title: "Restauration lancée" })
        setShowRestoreDialog(false)
      }
    } catch (e) {
      toast({ title: "Erreur", variant: "destructive" })
    }
  }

  const handleDelete = async (id: string) => {
    try {
      const token = typeof window !== "undefined" ? localStorage.getItem("auth_token") : null
      const res = await fetch(`/api/admin/backups/${id}`, {
        method: "DELETE",
        headers: token ? { Authorization: `Bearer ${token}` } : {},
      })
      if (res.ok) {
        toast({ title: "Sauvegarde supprimée" })
        mutate()
      }
    } catch (e) {
      toast({ title: "Erreur", variant: "destructive" })
    }
  }

  const handleDownload = async (id: string) => {
    toast({ title: "Téléchargement en cours..." })
    // In production, this would trigger actual download
  }

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <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">Sauvegardes</h1>
          <p className="text-zinc-400 text-sm">Gestion des sauvegardes de la base de données</p>
        </div>
        <div className="flex gap-2">
          <Button
            variant="outline"
            className="border-zinc-700 text-zinc-300 bg-transparent"
            onClick={() => setShowRestoreDialog(true)}
          >
            <Upload className="w-4 h-4 mr-2" />
            Restaurer
          </Button>
          <Button
            onClick={() => {
              setShowCreateDialog(true)
              startBackup()
            }}
            className="bg-purple-600 hover:bg-purple-700"
          >
            <Database className="w-4 h-4 mr-2" />
            Nouvelle sauvegarde
          </Button>
        </div>
      </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">
              <Database className="w-5 h-5 text-purple-400" />
            </div>
            <div>
              <p className="text-xl font-bold text-white">{stats.total}</p>
              <p className="text-zinc-400 text-sm">Sauvegardes</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">
              <CheckCircle className="w-5 h-5 text-green-400" />
            </div>
            <div>
              <p className="text-xl font-bold text-white">
                {stats.lastBackup ? new Date(stats.lastBackup).toLocaleDateString("fr-FR") : "-"}
              </p>
              <p className="text-zinc-400 text-sm">Dernière backup</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-blue-500/20">
              <HardDrive className="w-5 h-5 text-blue-400" />
            </div>
            <div>
              <p className="text-xl font-bold text-white">{stats.totalSize}</p>
              <p className="text-zinc-400 text-sm">Espace utilisé</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-yellow-500/20">
              <Clock className="w-5 h-5 text-yellow-400" />
            </div>
            <div>
              <p className="text-xl font-bold text-white">{stats.autoTime}</p>
              <p className="text-zinc-400 text-sm">Backup auto</p>
            </div>
          </div>
        </div>
      </div>

      {/* Current Backup Progress */}
      {isBackingUp && (
        <div className="bg-purple-500/10 rounded-xl border border-purple-500/30 p-4">
          <div className="flex items-center justify-between mb-2">
            <div className="flex items-center gap-2">
              <RefreshCw className="w-4 h-4 text-purple-400 animate-spin" />
              <span className="text-purple-300 font-medium">Sauvegarde en cours...</span>
            </div>
            <span className="text-purple-400">{backupProgress}%</span>
          </div>
          <Progress value={backupProgress} className="h-2 bg-purple-950" />
        </div>
      )}

      {/* Backups List */}
      {backups.length === 0 ? (
        <div className="text-center py-16 bg-zinc-800/50 rounded-xl border border-zinc-700/50">
          <Database className="w-16 h-16 mx-auto mb-4 text-zinc-600" />
          <h3 className="text-xl font-medium text-white mb-2">Aucune sauvegarde</h3>
          <p className="text-zinc-400 mb-6">Créez votre première sauvegarde de la base de données</p>
          <Button
            onClick={() => {
              setShowCreateDialog(true)
              startBackup()
            }}
            className="bg-purple-600 hover:bg-purple-700"
          >
            <Database className="w-4 h-4 mr-2" />
            Créer une sauvegarde
          </Button>
        </div>
      ) : (
        <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 overflow-hidden">
          <table className="w-full">
            <thead>
              <tr className="border-b border-zinc-700/50">
                <th className="p-4 text-left text-sm font-medium text-zinc-400">Nom</th>
                <th className="p-4 text-left text-sm font-medium text-zinc-400 hidden md:table-cell">Type</th>
                <th className="p-4 text-left text-sm font-medium text-zinc-400 hidden lg:table-cell">Taille</th>
                <th className="p-4 text-left text-sm font-medium text-zinc-400">Date</th>
                <th className="p-4 text-right text-sm font-medium text-zinc-400">Actions</th>
              </tr>
            </thead>
            <tbody>
              {backups.map((backup: any) => (
                <tr key={backup.id} className="border-b border-zinc-700/30 hover:bg-zinc-700/20 transition-colors">
                  <td className="p-4">
                    <div className="flex items-center gap-3">
                      <Database className="w-5 h-5 text-purple-400" />
                      <span className="text-white font-mono text-sm">{backup.name}</span>
                    </div>
                  </td>
                  <td className="p-4 hidden md:table-cell">
                    <Badge
                      className={
                        backup.backup_type === "auto"
                          ? "bg-blue-500/20 text-blue-400 border-0"
                          : "bg-purple-500/20 text-purple-400 border-0"
                      }
                    >
                      {backup.backup_type === "auto" ? "Automatique" : "Manuel"}
                    </Badge>
                  </td>
                  <td className="p-4 text-zinc-400 hidden lg:table-cell">
                    {backup.file_size ? `${(backup.file_size / 1024 / 1024).toFixed(2)} MB` : "-"}
                  </td>
                  <td className="p-4 text-zinc-400">
                    {backup.created_at ? new Date(backup.created_at).toLocaleString("fr-FR") : "-"}
                  </td>
                  <td className="p-4 text-right">
                    <div className="flex justify-end gap-2">
                      <Button
                        variant="ghost"
                        size="icon"
                        className="text-zinc-400 hover:text-white"
                        onClick={() => handleDownload(backup.id)}
                      >
                        <Download className="w-4 h-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="icon"
                        className="text-red-400 hover:text-red-300"
                        onClick={() => handleDelete(backup.id)}
                      >
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* Create Backup Dialog */}
      <Dialog open={showCreateDialog} onOpenChange={setShowCreateDialog}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
          <DialogHeader>
            <DialogTitle>Nouvelle sauvegarde</DialogTitle>
            <DialogDescription className="text-zinc-400">
              {isBackingUp ? "Sauvegarde en cours..." : "Sauvegarde terminée avec succès"}
            </DialogDescription>
          </DialogHeader>
          <div className="py-4">
            {isBackingUp ? (
              <div className="space-y-4">
                <div className="flex items-center justify-center">
                  <RefreshCw className="w-12 h-12 text-purple-400 animate-spin" />
                </div>
                <Progress value={backupProgress} className="h-2" />
                <p className="text-center text-zinc-400">{backupProgress}% complété</p>
              </div>
            ) : (
              <div className="flex flex-col items-center gap-4">
                <CheckCircle className="w-12 h-12 text-green-400" />
                <p className="text-green-400">Sauvegarde créée avec succès!</p>
              </div>
            )}
          </div>
          <DialogFooter>
            <Button onClick={() => setShowCreateDialog(false)} disabled={isBackingUp}>
              {isBackingUp ? "Veuillez patienter..." : "Fermer"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Restore Dialog */}
      <Dialog open={showRestoreDialog} onOpenChange={setShowRestoreDialog}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2 text-yellow-400">
              <AlertTriangle className="w-5 h-5" />
              Restaurer une sauvegarde
            </DialogTitle>
            <DialogDescription className="text-zinc-400">
              Attention: Cette action écrasera toutes les données actuelles.
            </DialogDescription>
          </DialogHeader>
          <div className="py-4 space-y-4">
            <div className="space-y-2">
              <Label>Sélectionner une sauvegarde</Label>
              <Select value={selectedBackup} onValueChange={setSelectedBackup}>
                <SelectTrigger className="bg-zinc-800 border-zinc-700">
                  <SelectValue placeholder="Choisir une sauvegarde" />
                </SelectTrigger>
                <SelectContent className="bg-zinc-800 border-zinc-700">
                  {backups.map((backup: any) => (
                    <SelectItem key={backup.id} value={backup.id}>
                      {backup.name} ({backup.created_at ? new Date(backup.created_at).toLocaleDateString("fr-FR") : "-"}
                      )
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowRestoreDialog(false)}>
              Annuler
            </Button>
            <Button className="bg-yellow-600 hover:bg-yellow-700" onClick={handleRestore}>
              Restaurer
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
