"use client";

import { useState, useEffect, useCallback } from "react";
import { 
  Users, 
  Crown, 
  Shield, 
  Trash2, 
  Search, 
  BadgeCheck, 
  ChevronLeft, 
  ChevronRight,
  Sparkles,
  Loader2,
  RefreshCw,
  AlertTriangle
} from "lucide-react";
import { formatDate } from "@/lib/utils";
import { toast } from "@/components/ui/Toaster";

export default function AdminUsersPage() {
  const [users, setUsers] = useState<any[]>([]);
  const [stats, setStats] = useState({ total: 0, vipCount: 0, adminCount: 0, freeCount: 0 });
  const [pagination, setPagination] = useState({ page: 1, totalPages: 1, limit: 25, total: 0 });
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [debouncedSearch, setDebouncedSearch] = useState("");
  const [actionLoading, setActionLoading] = useState<string | null>(null);
  const [cleaningFakes, setCleaningFakes] = useState(false);

  // Debounce search input
  useEffect(() => {
    const handler = setTimeout(() => setDebouncedSearch(search), 350);
    return () => clearTimeout(handler);
  }, [search]);

  const fetchUsers = useCallback(async (page = 1, searchQuery = debouncedSearch) => {
    setLoading(true);
    try {
      const sp = new URLSearchParams();
      sp.set("page", String(page));
      sp.set("limit", "25");
      if (searchQuery.trim()) sp.set("search", searchQuery.trim());

      const res = await fetch(`/api/admin/users?${sp.toString()}`);
      const data = await res.json();

      if (res.ok) {
        setUsers(data.users || []);
        if (data.pagination) setPagination(data.pagination);
        if (data.stats) setStats(data.stats);
      } else {
        toast(data.error || "Erreur de chargement", "error");
      }
    } catch {
      toast("Erreur réseau", "error");
    } finally {
      setLoading(false);
    }
  }, [debouncedSearch]);

  useEffect(() => {
    fetchUsers(1, debouncedSearch);
  }, [debouncedSearch, fetchUsers]);

  const updateUser = async (id: string, payload: any) => {
    setActionLoading(id);
    try {
      const res = await fetch("/api/admin/users", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id, ...payload }),
      });
      const data = await res.json();
      if (res.ok) {
        toast("Utilisateur mis à jour", "success");
        fetchUsers(pagination.page);
      } else {
        toast(data.error || "Erreur", "error");
      }
    } catch {
      toast("Erreur de connexion", "error");
    } finally {
      setActionLoading(null);
    }
  };

  const deleteUser = async (id: string, name: string) => {
    if (!confirm(`Supprimer définitivement l'utilisateur "${name || 'Anonyme'}" ?`)) return;
    await updateUser(id, { action: "delete" });
  };

  const cleanupFakeAccounts = async () => {
    if (!confirm("Voulez-vous supprimer automatiquement tous les faux comptes générés (@streamvibe.local) et ne conserver que les vrais utilisateurs ?")) return;
    setCleaningFakes(true);
    try {
      const res = await fetch("/api/admin/users", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "cleanup_fakes" }),
      });
      const data = await res.json();
      if (res.ok) {
        toast(`Nettoyage terminé ! ${data.deletedCount || 0} faux comptes supprimés.`, "success");
        fetchUsers(1);
      } else {
        toast(data.error || "Erreur de nettoyage", "error");
      }
    } catch {
      toast("Erreur lors du nettoyage", "error");
    } finally {
      setCleaningFakes(false);
    }
  };

  const roleColors: Record<string, string> = {
    SUPERADMIN: "#f59e0b",
    ADMIN: "#e05a68",
    MODERATOR: "#3b82f6",
    EDITOR: "#10b981",
    USER: "#887799",
  };

  return (
    <div className="p-4 sm:p-6 md:p-8 space-y-6 animate-fade-in text-white">
      
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-[#231538] pb-5">
        <div>
          <h1 className="text-2xl sm:text-3xl font-black tracking-tight text-white flex items-center gap-2.5">
            <Users className="text-[#e05a68]" />
            <span>Gestion des Utilisateurs</span>
          </h1>
          <p className="text-xs text-[#a08ca8] mt-1">
            {stats.total} comptes réels enregistrés • {stats.vipCount} membres VIP
          </p>
        </div>

        <div className="flex items-center gap-2">
          {/* Bouton Nettoyage Faux Comptes */}
          <button
            onClick={cleanupFakeAccounts}
            disabled={cleaningFakes}
            className="px-4 py-2.5 rounded-xl bg-gradient-to-r from-red-600/20 to-pink-600/20 border border-red-500/40 text-red-300 hover:text-white hover:border-red-500 text-xs font-black flex items-center gap-2 shadow-lg active:scale-95 transition-all cursor-pointer"
            title="Supprimer les comptes fictifs @streamvibe.local"
          >
            {cleaningFakes ? (
              <Loader2 size={14} className="animate-spin" />
            ) : (
              <Sparkles size={14} className="text-red-400" />
            )}
            <span>Nettoyer les faux comptes</span>
          </button>

          {/* Bouton Actualiser */}
          <button
            onClick={() => fetchUsers(pagination.page)}
            className="p-2.5 rounded-xl bg-white/5 border border-white/10 hover:bg-white/10 text-[#a38890] hover:text-white transition-all cursor-pointer"
            title="Actualiser la liste"
          >
            <RefreshCw size={15} />
          </button>
        </div>
      </div>

      {/* Cartes de statistiques */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3 sm:gap-4">
        {[
          { label: "Utilisateurs Réels", value: stats.total, icon: Users, color: "#e05a68", bg: "bg-[#e05a68]/10 border-[#e05a68]/30" },
          { label: "Membres VIP", value: stats.vipCount, icon: Crown, color: "#f59e0b", bg: "bg-amber-500/10 border-amber-500/30" },
          { label: "Administrateurs", value: stats.adminCount, icon: Shield, color: "#3b82f6", bg: "bg-blue-500/10 border-blue-500/30" },
          { label: "Comptes Gratuits", value: stats.freeCount, icon: Users, color: "#10b981", bg: "bg-emerald-500/10 border-emerald-500/30" },
        ].map(({ label, value, icon: Icon, color, bg }) => (
          <div key={label} className={`p-4 rounded-2xl border ${bg} text-center space-y-1 backdrop-blur-md`}>
            <Icon size={18} className="mx-auto" style={{ color }} />
            <div className="text-xl sm:text-2xl font-black" style={{ color }}>{value}</div>
            <p className="text-[11px] font-bold text-[#887799]">{label}</p>
          </div>
        ))}
      </div>

      {/* Barre de Recherche */}
      <div className="relative">
        <Search size={16} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-[#887799]" />
        <input
          type="text"
          value={search}
          onChange={e => setSearch(e.target.value)}
          placeholder="Rechercher par nom ou email (ex: admin@madetobreakrules.com)..."
          className="w-full h-11 pl-10 pr-4 bg-[#12080b] border border-[#2e1217] focus:border-[#e05a68] rounded-xl text-xs text-white placeholder-[#665577] outline-none transition-all"
        />
        {search && (
          <button 
            onClick={() => setSearch("")}
            className="absolute right-3 top-1/2 -translate-y-1/2 text-xs text-[#887799] hover:text-white px-1.5 py-0.5"
          >
            Effacer
          </button>
        )}
      </div>

      {/* Table des Utilisateurs */}
      {loading ? (
        <div className="space-y-2">
          {[...Array(5)].map((_, i) => (
            <div key={i} className="h-16 w-full rounded-2xl bg-[#120c22] border border-[#231538] animate-pulse" />
          ))}
        </div>
      ) : users.length === 0 ? (
        <div className="text-center py-12 bg-[#0e0917] border border-[#231538] rounded-2xl p-6 space-y-2">
          <Users size={32} className="mx-auto text-[#887799]" />
          <p className="text-sm font-bold text-[#a38890]">Aucun utilisateur trouvé</p>
          <p className="text-xs text-[#887799]">Modifie tes critères de recherche ou réinitialise le filtre.</p>
        </div>
      ) : (
        <div className="bg-[#0e0917] border border-[#231538] rounded-2xl overflow-hidden shadow-2xl">
          <div className="overflow-x-auto">
            <table className="w-full text-left text-xs">
              <thead>
                <tr className="border-b border-[#231538] bg-[#140d24] text-[#887799] font-black uppercase text-[10px] tracking-wider">
                  <th className="px-4 py-3.5">Utilisateur</th>
                  <th className="px-4 py-3.5">Rôle</th>
                  <th className="px-4 py-3.5">Statut VIP</th>
                  <th className="px-4 py-3.5">Certifié</th>
                  <th className="px-4 py-3.5">Inscrit le</th>
                  <th className="px-4 py-3.5 text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-[#1b102c]">
                {users.map((u) => {
                  const isProcessing = actionLoading === u.id;
                  return (
                    <tr key={u.id} className="hover:bg-white/[0.02] transition-colors">
                      
                      {/* Nom & Email */}
                      <td className="px-4 py-3.5">
                        <div className="flex items-center gap-3">
                          <div className="w-9 h-9 rounded-xl bg-gradient-to-tr from-[#5c1922] to-[#e05a68] p-0.5 flex-shrink-0 overflow-hidden shadow-md">
                            {u.image ? (
                              <img src={u.image} alt={u.name || "User"} className="w-full h-full object-cover rounded-[10px]" />
                            ) : (
                              <div className="w-full h-full rounded-[10px] bg-[#160d26] flex items-center justify-center font-black text-white text-xs">
                                {(u.name || u.email || "U")[0].toUpperCase()}
                              </div>
                            )}
                          </div>
                          <div className="min-w-0">
                            <p className="font-bold text-white truncate">{u.name || "Sans nom"}</p>
                            <p className="text-[11px] text-[#887799] truncate">{u.email}</p>
                          </div>
                        </div>
                      </td>

                      {/* Rôle Sélecteur */}
                      <td className="px-4 py-3.5">
                        <select
                          value={u.role}
                          disabled={isProcessing}
                          onChange={(e) => updateUser(u.id, { role: e.target.value })}
                          className="px-2.5 py-1 rounded-lg bg-[#140c24] border border-[#311c4d] text-xs font-black outline-none cursor-pointer"
                          style={{ color: roleColors[u.role] || "#fff" }}
                        >
                          <option value="USER">USER</option>
                          <option value="ADMIN">ADMIN</option>
                          <option value="SUPERADMIN">SUPERADMIN</option>
                          <option value="MODERATOR">MODÉRATEUR</option>
                          <option value="EDITOR">ÉDITEUR</option>
                        </select>
                      </td>

                      {/* VIP Toggle */}
                      <td className="px-4 py-3.5">
                        <button
                          onClick={() => updateUser(u.id, { isPremium: !u.isPremium })}
                          disabled={isProcessing}
                          className={`px-3 py-1 rounded-full text-[10px] font-black uppercase tracking-wider flex items-center gap-1.5 transition-all cursor-pointer ${
                            u.isPremium 
                              ? "bg-amber-500/20 text-amber-300 border border-amber-500/40 shadow-[0_0_10px_rgba(245,158,11,0.2)]" 
                              : "bg-white/5 text-[#887799] border border-white/10 hover:text-white"
                          }`}
                        >
                          <Crown size={12} className={u.isPremium ? "text-amber-400 fill-amber-400" : ""} />
                          <span>{u.isPremium ? "VIP ACTIF" : "GRATUIT"}</span>
                        </button>
                      </td>

                      {/* Badge Certifié */}
                      <td className="px-4 py-3.5">
                        <button
                          onClick={() => updateUser(u.id, { isVerified: !u.isVerified })}
                          disabled={isProcessing}
                          className={`p-1.5 rounded-lg border transition-all cursor-pointer ${
                            u.isVerified 
                              ? "bg-[#e05a68]/20 text-[#e05a68] border-[#e05a68]/50" 
                              : "bg-white/5 text-[#887799] border-white/10 hover:text-white"
                          }`}
                          title={u.isVerified ? "Créateur Vérifié" : "Non Vérifié"}
                        >
                          <BadgeCheck size={16} />
                        </button>
                      </td>

                      {/* Date d'inscription */}
                      <td className="px-4 py-3.5 text-[#887799]">
                        {formatDate(u.createdAt)}
                      </td>

                      {/* Actions */}
                      <td className="px-4 py-3.5 text-right">
                        <button
                          onClick={() => deleteUser(u.id, u.name || u.email)}
                          disabled={isProcessing || u.role === "SUPERADMIN"}
                          className="p-2 rounded-xl bg-red-500/10 hover:bg-red-500/20 text-red-400 hover:text-red-300 border border-red-500/20 transition-all cursor-pointer disabled:opacity-30 disabled:cursor-not-allowed"
                          title="Supprimer définitivement"
                        >
                          <Trash2 size={14} />
                        </button>
                      </td>

                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>

          {/* Pagination */}
          {pagination.totalPages > 1 && (
            <div className="p-4 border-t border-[#231538] flex items-center justify-between bg-[#120c22]">
              <p className="text-xs text-[#887799]">
                Page <span className="font-bold text-white">{pagination.page}</span> sur <span className="font-bold text-white">{pagination.totalPages}</span> ({pagination.total} utilisateurs)
              </p>
              
              <div className="flex items-center gap-2">
                <button
                  onClick={() => fetchUsers(pagination.page - 1)}
                  disabled={pagination.page <= 1}
                  className="px-3 py-1.5 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-xs font-bold disabled:opacity-30 disabled:cursor-not-allowed flex items-center gap-1"
                >
                  <ChevronLeft size={14} /> Précédent
                </button>
                <button
                  onClick={() => fetchUsers(pagination.page + 1)}
                  disabled={pagination.page >= pagination.totalPages}
                  className="px-3 py-1.5 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-xs font-bold disabled:opacity-30 disabled:cursor-not-allowed flex items-center gap-1"
                >
                  Suivant <ChevronRight size={14} />
                </button>
              </div>
            </div>
          )}
        </div>
      )}

    </div>
  );
}


