'use client';

import { useState, useEffect, useCallback } from 'react';
import { adminService } from '@/services/admin.service';
import type { AdminInfo, RoleInfo, AuditLogEntry, AdminLogEntry, PermissionInfo } from '@/types/admin.types';
import { cn, formatDateTime } from '@/lib/utils';
import { usePriorityData } from '@/hooks/usePriorityData';
import { useSystemConfig } from '@/hooks/useSystemConfig';
import { TableSkeleton } from '@/components/priority/skeletons';
import {
  Search, Plus, Pencil, Trash2, Shield, ShieldOff, RotateCcw, Eye, ChevronDown, ChevronUp, X,
  Filter, Download, Upload, MoreHorizontal, UserCheck, UserX, AlertTriangle, Key, Users, FileText,
  ChevronLeft, ChevronRight, Loader2, CheckCircle2, XCircle, AlertCircle, ClipboardList,
  RefreshCw, UserCog, Ban, ShieldCheck
} from 'lucide-react';

type Tab = 'list' | 'audit';
type StatusFilter = 'all' | 'active' | 'inactive' | 'banned';

function ConfirmDialog({
  title, description, confirmLabel, confirmVariant = 'danger', onConfirm, onClose, loading,
  extraField, extraFieldLabel, extraFieldPlaceholder
}: {
  title: string;
  description: string;
  confirmLabel: string;
  confirmVariant?: 'danger' | 'primary' | 'warning';
  onConfirm: (reason: string) => void;
  onClose: () => void;
  loading?: boolean;
  extraField?: string;
  extraFieldLabel?: string;
  extraFieldPlaceholder?: string;
}) {
  const [reason, setReason] = useState('');
  const [extra, setExtra] = useState('');

  const handleConfirm = () => {
    if (!reason.trim()) return;
    onConfirm(reason.trim());
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4" onClick={onClose}>
      <div className="w-full max-w-lg rounded-xl border border-white/10 bg-slate-900 shadow-2xl" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between border-b border-white/10 p-5">
          <h2 className="text-lg font-semibold text-white">{title}</h2>
          <button onClick={onClose} className="rounded-lg p-1 text-slate-400 hover:text-white">
            <X className="h-5 w-5" />
          </button>
        </div>
        <div className="p-5">
          <p className="text-sm text-slate-400">{description}</p>
          <div className="mt-4 space-y-3">
            <div>
              <label className="mb-1 block text-sm font-medium text-slate-300">Reason <span className="text-red-400">*</span></label>
              <textarea
                value={reason}
                onChange={(e) => setReason(e.target.value)}
                placeholder="Provide a reason for this action..."
                rows={3}
                className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-white placeholder:text-slate-400 focus:border-blue-500 focus:outline-none resize-none"
              />
            </div>
            {extraField && (
              <div>
                <label className="mb-1 block text-sm font-medium text-slate-300">{extraFieldLabel || extraField}</label>
                <input
                  type={extraField === 'password' ? 'password' : 'text'}
                  value={extra}
                  onChange={(e) => setExtra(e.target.value)}
                  placeholder={extraFieldPlaceholder || ''}
                  className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-white placeholder:text-slate-400 focus:border-blue-500 focus:outline-none"
                />
              </div>
            )}
          </div>
        </div>
        <div className="flex justify-end gap-3 border-t border-white/10 p-5">
          <button
            onClick={onClose}
            className="rounded-lg border border-white/10 px-4 py-2 text-sm text-slate-300 hover:bg-white/5"
          >
            Cancel
          </button>
          <button
            onClick={handleConfirm}
            disabled={!!(loading || !reason.trim() || (extraField && !(extra?.trim?.())))}
            className={cn(
              'rounded-lg px-4 py-2 text-sm font-semibold text-white disabled:opacity-50',
              confirmVariant === 'danger' && 'bg-red-600 hover:bg-red-700',
              confirmVariant === 'primary' && 'bg-blue-600 hover:bg-blue-700',
              confirmVariant === 'warning' && 'bg-amber-600 hover:bg-amber-700',
            )}
          >
            {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : confirmLabel}
          </button>
        </div>
      </div>
    </div>
  );
}

function AdminFormDialog({
  admin, roles, onClose, onSuccess,
}: {
  admin: AdminInfo | null;
  roles: RoleInfo[];
  onClose: () => void;
  onSuccess: () => void;
}) {
  const [name, setName] = useState(admin?.name || '');
  const [username, setUsername] = useState(admin?.username || '');
  const [email, setEmail] = useState(admin?.email || '');
  const [phone, setPhone] = useState(admin?.phone || '');
  const [roleId, setRoleId] = useState(admin?.role?.id || '');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const isEdit = !!admin;

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setLoading(true);
    try {
      if (isEdit) {
        await adminService.updateAdmin(admin.id, { name, email, phone, roleId: roleId || undefined });
      } else {
        if (!password) { setError('Password is required'); setLoading(false); return; }
        await adminService.createAdmin({ name, username, email, password, phone, roleId: roleId || undefined });
      }
      onSuccess();
      onClose();
    } catch (err: any) {
      setError(err?.message || `Failed to ${isEdit ? 'update' : 'create'} admin`);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4" onClick={onClose}>
      <div className="w-full max-w-lg rounded-xl border border-white/10 bg-slate-900 shadow-2xl max-h-[90vh] overflow-y-auto" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between border-b border-white/10 p-5">
          <h2 className="text-lg font-semibold text-white">{isEdit ? 'Edit Admin' : 'Create Admin'}</h2>
          <button onClick={onClose} className="rounded-lg p-1 text-slate-400 hover:text-white"><X className="h-5 w-5" /></button>
        </div>
        <form onSubmit={handleSubmit} className="p-5 space-y-4">
          {error && <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-400">{error}</div>}
          {!isEdit && (
            <div>
              <label className="mb-1 block text-sm font-medium text-slate-300">Username <span className="text-red-400">*</span></label>
              <input type="text" value={username} onChange={(e) => setUsername(e.target.value)} required placeholder="admin_username" className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-white placeholder:text-slate-400 focus:border-blue-500 focus:outline-none" />
            </div>
          )}
          <div>
            <label className="mb-1 block text-sm font-medium text-slate-300">Name <span className="text-red-400">*</span></label>
            <input type="text" value={name} onChange={(e) => setName(e.target.value)} required placeholder="Full Name" className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-white placeholder:text-slate-400 focus:border-blue-500 focus:outline-none" />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium text-slate-300">Email <span className="text-red-400">*</span></label>
            <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required placeholder="admin@example.com" className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-white placeholder:text-slate-400 focus:border-blue-500 focus:outline-none" />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium text-slate-300">Phone</label>
            <input type="tel" value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="+1234567890" className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-white placeholder:text-slate-400 focus:border-blue-500 focus:outline-none" />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium text-slate-300">Role</label>
            <select value={roleId} onChange={(e) => setRoleId(e.target.value)} className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-white focus:border-blue-500 focus:outline-none">
              <option value="">Select Role</option>
              {(roles || []).map((r) => <option key={r.id} value={r.id}>{r.name}</option>)}
            </select>
          </div>
          {!isEdit && (
            <div>
              <label className="mb-1 block text-sm font-medium text-slate-300">Password <span className="text-red-400">*</span></label>
              <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} required placeholder="Secure password" className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-white placeholder:text-slate-400 focus:border-blue-500 focus:outline-none" />
            </div>
          )}
          <div className="flex justify-end gap-3 border-t border-white/10 pt-4">
            <button type="button" onClick={onClose} className="rounded-lg border border-white/10 px-4 py-2 text-sm text-slate-300 hover:bg-white/5">Cancel</button>
            <button type="submit" disabled={loading} className="rounded-lg bg-blue-600 px-4 py-2 text-sm font-semibold text-white hover:bg-blue-700 disabled:opacity-50">{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : (isEdit ? 'Update Admin' : 'Create Admin')}</button>
          </div>
        </form>
      </div>
    </div>
  );
}

function PermissionsDialog({
  admin, roles, onClose, onSuccess,
}: {
  admin: AdminInfo;
  roles: RoleInfo[];
  onClose: () => void;
  onSuccess: () => void;
}) {
  const [selectedRoleId, setSelectedRoleId] = useState(admin.role?.id || '');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const role = roles.find(r => r.id === selectedRoleId);
  const moduleMap: Record<string, PermissionInfo[]> = {};

  if (role?.permissions) {
    role.permissions.forEach((rp) => {
      const mod = rp.permission.module || 'General';
      if (!moduleMap[mod]) moduleMap[mod] = [];
      moduleMap[mod].push(rp.permission as any);
    });
  }

  const handleSave = async () => {
    setError(null);
    setLoading(true);
    try {
      await adminService.updateAdmin(admin.id, { roleId: selectedRoleId || undefined });
      onSuccess();
      onClose();
    } catch (err: any) {
      setError(err?.message || 'Failed to update role');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4" onClick={onClose}>
      <div className="w-full max-w-2xl rounded-xl border border-white/10 bg-slate-900 shadow-2xl max-h-[90vh] overflow-y-auto" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between border-b border-white/10 p-5">
          <div>
            <h2 className="text-lg font-semibold text-white">Manage Permissions</h2>
            <p className="text-sm text-slate-400">{admin.name} ({admin.email})</p>
          </div>
          <button onClick={onClose} className="rounded-lg p-1 text-slate-400 hover:text-white"><X className="h-5 w-5" /></button>
        </div>
        <div className="p-5 space-y-4">
          {error && <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-400">{error}</div>}
          <div>
            <label className="mb-1 block text-sm font-medium text-slate-300">Assign Role</label>
            <select value={selectedRoleId} onChange={(e) => setSelectedRoleId(e.target.value)} className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-white focus:border-blue-500 focus:outline-none">
              <option value="">No Role</option>
              {roles.map((r) => <option key={r.id} value={r.id}>{r.name} {r.isSystem ? '(System)' : ''}</option>)}
            </select>
          </div>
          <div className="space-y-3">
            <h3 className="text-sm font-medium text-slate-300">Current Permissions</h3>
            {Object.keys(moduleMap).length === 0 ? (
              <p className="text-sm text-slate-500">No permissions assigned to this role.</p>
            ) : (
              Object.entries(moduleMap).map(([mod, perms]) => (
                <div key={mod} className="rounded-lg border border-white/10 bg-white/5 p-3">
                  <h4 className="text-xs font-semibold uppercase text-slate-400 mb-2">{mod}</h4>
                  <div className="flex flex-wrap gap-2">
                    {perms.map((p) => (
                      <span key={p.id} className="rounded-full bg-blue-500/20 px-2 py-1 text-xs text-blue-300">{p.name || p.key}</span>
                    ))}
                  </div>
                </div>
              ))
            )}
          </div>
        </div>
        <div className="flex justify-end gap-3 border-t border-white/10 p-5">
          <button onClick={onClose} className="rounded-lg border border-white/10 px-4 py-2 text-sm text-slate-300 hover:bg-white/5">Cancel</button>
          <button onClick={handleSave} disabled={loading} className="rounded-lg bg-blue-600 px-4 py-2 text-sm font-semibold text-white hover:bg-blue-700 disabled:opacity-50">{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Save Changes'}</button>
        </div>
      </div>
    </div>
  );
}

function AuditTab({ adminId, adminName }: { adminId: string; adminName: string }) {
  const [logs, setLogs] = useState<AdminLogEntry[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [page, setPage] = useState(1);
  const [meta, setMeta] = useState({ total: 0, totalPages: 0 });

  const loadLogs = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await adminService.getAdminLogs({ actorUserId: adminId, page, limit: 10 });
      setLogs(res.data || []);
      setMeta({ total: res.meta.total, totalPages: res.meta.totalPages });
    } catch (err: any) {
      setError(err?.message || 'Failed to load audit logs');
    } finally {
      setLoading(false);
    }
  }, [adminId, page]);

  useEffect(() => { loadLogs(); }, [loadLogs]);

  const actionColors: Record<string, string> = {
    CREATE: 'bg-emerald-500/20 text-emerald-300',
    UPDATE: 'bg-blue-500/20 text-blue-300',
    DELETE: 'bg-red-500/20 text-red-300',
    BAN: 'bg-orange-500/20 text-orange-300',
    UNBAN: 'bg-green-500/20 text-green-300',
    RESET_PASSWORD: 'bg-amber-500/20 text-amber-300',
    SUSPEND: 'bg-red-500/20 text-red-300',
    ACTIVATE: 'bg-green-500/20 text-green-300',
    TERMINATE: 'bg-red-500/20 text-red-300',
  };

  return (
    <div className="space-y-4">
      <h3 className="text-sm font-medium text-slate-300">Audit History for {adminName}</h3>
      {error && <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-400">{error}</div>}
      {loading ? (
        <div className="flex items-center justify-center py-8"><Loader2 className="h-6 w-6 animate-spin text-slate-400" /></div>
      ) : logs.length === 0 ? (
        <div className="rounded-lg border border-white/10 bg-white/5 px-4 py-8 text-center text-sm text-slate-400">No audit logs found.</div>
      ) : (
        <div className="space-y-2">
          {logs.map((log) => (
            <div key={log.id} className="rounded-lg border border-white/10 bg-white/5 p-3">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <span className={cn('rounded-full px-2 py-0.5 text-xs font-semibold', actionColors[log.action] || 'bg-slate-500/20 text-slate-300')}>{log.action}</span>
                  <span className="text-xs text-slate-400">{log.resource || 'N/A'}</span>
                </div>
                <span className="text-xs text-slate-500">{formatDateTime(log.createdAt)}</span>
              </div>
              {log.details && <p className="mt-1 text-sm text-slate-300">{log.details}</p>}
              <div className="mt-1 flex items-center gap-3 text-xs text-slate-500">
                {log.ipAddress && <span>IP: {log.ipAddress}</span>}
                {log.userAgent && <span className="truncate max-w-xs">{log.userAgent}</span>}
              </div>
            </div>
          ))}
          {meta.totalPages > 1 && (
            <div className="flex items-center justify-center gap-2 pt-2">
              <button onClick={() => setPage((p) => Math.max(1, p - 1))} disabled={page <= 1} className="rounded-lg border border-white/10 px-3 py-1.5 text-sm text-slate-300 hover:bg-white/5 disabled:opacity-50"><ChevronLeft className="h-4 w-4" /></button>
              <span className="text-sm text-slate-400">Page {page} of {meta.totalPages}</span>
              <button onClick={() => setPage((p) => Math.min(meta.totalPages, p + 1))} disabled={page >= meta.totalPages} className="rounded-lg border border-white/10 px-3 py-1.5 text-sm text-slate-300 hover:bg-white/5 disabled:opacity-50"><ChevronRight className="h-4 w-4" /></button>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

export default function SuperAdminAdminsPage() {
  const sysConfig = useSystemConfig();
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState<StatusFilter>('all');
  const [selectedAdmin, setSelectedAdmin] = useState<AdminInfo | null>(null);
  const [auditAdmin, setAuditAdmin] = useState<AdminInfo | null>(null);
  const [actionMenu, setActionMenu] = useState<string | null>(null);
  const [confirmAction, setConfirmAction] = useState<{ type: string; admin: AdminInfo } | null>(null);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [showForm, setShowForm] = useState(false);
  const [showPermissions, setShowPermissions] = useState(false);

  const { data: admins = [], loading, error, refetch } = usePriorityData<AdminInfo[]>({
    key: `admins:${search}:${statusFilter}`,
    fetcher: () => adminService.listAdmins({ search, status: statusFilter === 'all' ? undefined : statusFilter, page: 1, limit: 50 }).then(r => r.data || []),
    priority: 'high',
    ttl: 30_000,
  });

  const { data: roles = [] } = usePriorityData<RoleInfo[]>({
    key: 'roles:list',
    fetcher: () => adminService.listRoles(),
    priority: 'high',
    ttl: 60_000,
  });

  const handleAction = async (reason: string) => {
    if (!confirmAction) return;
    setConfirmLoading(true);
    try {
      switch (confirmAction.type) {
        case 'resetPassword':
          await adminService.resetPassword({ userId: confirmAction.admin.id, newPassword: sysConfig.defaultTempPassword });
          break;
        case 'suspend':
          await adminService.updateAdmin(confirmAction.admin.id, { isActive: false });
          await adminService.banAdmin(confirmAction.admin.id, reason);
          break;
        case 'activate':
          await adminService.updateAdmin(confirmAction.admin.id, { isActive: true });
          await adminService.unbanAdmin(confirmAction.admin.id, reason);
          break;
        case 'terminate':
          await adminService.deleteAdmin(confirmAction.admin.id);
          break;
      }
      refetch();
    } catch (err: any) {
      console.error(err);
    } finally {
      setConfirmLoading(false);
      setConfirmAction(null);
    }
  };

  const filteredAdmins = admins || [];

  return (
    <div className="space-y-6">
      <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">Admins</h1>
          <p className="text-slate-400">Create, manage, and monitor all admin accounts.</p>
        </div>
        <div className="flex items-center gap-2">
          <button onClick={() => { setSelectedAdmin(null); setShowForm(true); }} className="inline-flex items-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-sm font-semibold text-white hover:bg-blue-700">
            <Plus className="h-4 w-4" /> Add Admin
          </button>
        </div>
      </div>

      {error && (
        <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-400">{error.message || 'Error loading admins'}</div>
      )}

      <div className="flex flex-col gap-3 sm:flex-row">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
          <input
            type="text"
            placeholder="Search admins by email, name, or username..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full rounded-lg border border-white/10 bg-white/5 pl-10 pr-4 py-2 text-white placeholder:text-slate-400 focus:border-blue-500 focus:outline-none"
          />
        </div>
        <div className="relative">
          <Filter className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
          <select
            value={statusFilter}
            onChange={(e) => setStatusFilter(e.target.value as StatusFilter)}
            className="rounded-lg border border-white/10 bg-white/5 pl-10 pr-8 py-2 text-white focus:border-blue-500 focus:outline-none appearance-none"
          >
            <option value="all">All Status</option>
            <option value="active">Active</option>
            <option value="inactive">Inactive</option>
            <option value="banned">Banned</option>
          </select>
        </div>
      </div>

      {error && (
        <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-400">
          {error.message || 'Error loading admins'}
          <button onClick={() => refetch()} className="ml-4 underline">Retry</button>
        </div>
      )}

      {loading ? (
        <TableSkeleton rows={8} />
      ) : (
        <div className="rounded-xl border border-white/10 overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full text-left text-sm">
              <thead className="bg-white/5 text-xs uppercase text-slate-400">
                <tr>
                  <th className="px-4 py-3">Admin ID</th>
                  <th className="px-4 py-3">Name</th>
                  <th className="px-4 py-3">Username</th>
                  <th className="px-4 py-3">Email</th>
                  <th className="px-4 py-3">Status</th>
                  <th className="px-4 py-3">Role</th>
                  <th className="px-4 py-3">2FA</th>
                  <th className="px-4 py-3">Last Login</th>
                  <th className="px-4 py-3 text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-white/5">
                {filteredAdmins.map((admin) => (
                  <tr key={admin.id} className="hover:bg-white/5">
                    <td className="px-4 py-3 text-white font-mono text-xs">{admin.adminId}</td>
                    <td className="px-4 py-3 text-white">{admin.name}</td>
                    <td className="px-4 py-3 text-slate-300">{admin.username}</td>
                    <td className="px-4 py-3 text-slate-300">{admin.email}</td>
                    <td className="px-4 py-3">
                      {admin.isBanned ? (
                        <span className="inline-flex items-center gap-1 rounded-full bg-red-500/20 px-2 py-1 text-xs text-red-300"><XCircle className="h-3 w-3" /> Banned</span>
                      ) : admin.isActive ? (
                        <span className="inline-flex items-center gap-1 rounded-full bg-green-500/20 px-2 py-1 text-xs text-green-300"><CheckCircle2 className="h-3 w-3" /> Active</span>
                      ) : (
                        <span className="inline-flex items-center gap-1 rounded-full bg-yellow-500/20 px-2 py-1 text-xs text-yellow-300"><AlertCircle className="h-3 w-3" /> Inactive</span>
                      )}
                    </td>
                    <td className="px-4 py-3">
                      <span className="rounded-full bg-purple-500/20 px-2 py-1 text-xs text-purple-300">
                        {admin.role?.name || 'N/A'}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-slate-300">
                      <span className={cn(admin.twoFactorEnabled ? 'text-green-400' : 'text-red-400')}>
                        {admin.twoFactorEnabled ? 'Enabled' : 'Disabled'}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-slate-300">{admin.lastLoginAt ? formatDateTime(admin.lastLoginAt) : 'Never'}</td>
                    <td className="px-4 py-3">
                      <div className="relative flex items-center justify-end">
                        <button onClick={() => setActionMenu(actionMenu === admin.id ? null : admin.id)} className="rounded-lg p-1.5 text-slate-400 hover:text-white hover:bg-white/10">
                          <MoreHorizontal className="h-4 w-4" />
                        </button>
                        {actionMenu === admin.id && (
                          <div className="absolute right-0 top-8 z-20 w-48 rounded-xl border border-white/10 bg-slate-800 shadow-xl py-1">
                            <button onClick={() => { setSelectedAdmin(admin); setShowForm(true); setActionMenu(null); }} className="flex w-full items-center gap-2 px-4 py-2 text-sm text-slate-300 hover:bg-white/5 hover:text-white"><Pencil className="h-4 w-4" /> Edit</button>
                            <button onClick={() => { setConfirmAction({ type: 'resetPassword', admin }); setActionMenu(null); }} className="flex w-full items-center gap-2 px-4 py-2 text-sm text-slate-300 hover:bg-white/5 hover:text-white"><Key className="h-4 w-4" /> Reset Password</button>
                            <button onClick={() => { setShowPermissions(true); setSelectedAdmin(admin); setActionMenu(null); }} className="flex w-full items-center gap-2 px-4 py-2 text-sm text-slate-300 hover:bg-white/5 hover:text-white"><Shield className="h-4 w-4" /> Permissions</button>
                            <button onClick={() => { setAuditAdmin(admin); setActionMenu(null); }} className="flex w-full items-center gap-2 px-4 py-2 text-sm text-slate-300 hover:bg-white/5 hover:text-white"><ClipboardList className="h-4 w-4" /> Audit History</button>
                            <div className="my-1 border-t border-white/10" />
                            {admin.isBanned ? (
                              <button onClick={() => { setConfirmAction({ type: 'activate', admin }); setActionMenu(null); }} className="flex w-full items-center gap-2 px-4 py-2 text-sm text-green-400 hover:bg-white/5"><UserCheck className="h-4 w-4" /> Activate</button>
                            ) : (
                              <button onClick={() => { setConfirmAction({ type: 'ban', admin }); setActionMenu(null); }} className="flex w-full items-center gap-2 px-4 py-2 text-sm text-red-400 hover:bg-white/5"><Ban className="h-4 w-4" /> Ban</button>
                            )}
                            {admin.isBanned && (
                              <button onClick={() => { setConfirmAction({ type: 'unban', admin }); setActionMenu(null); }} className="flex w-full items-center gap-2 px-4 py-2 text-sm text-emerald-400 hover:bg-white/5"><ShieldCheck className="h-4 w-4" /> Unban</button>
                            )}
                            {!admin.isBanned && admin.isActive && (
                              <button onClick={() => { setConfirmAction({ type: 'suspend', admin }); setActionMenu(null); }} className="flex w-full items-center gap-2 px-4 py-2 text-sm text-amber-400 hover:bg-white/5"><ShieldOff className="h-4 w-4" /> Suspend</button>
                            )}
                            <button onClick={() => { setConfirmAction({ type: 'terminate', admin }); setActionMenu(null); }} className="flex w-full items-center gap-2 px-4 py-2 text-sm text-red-400 hover:bg-white/5"><Trash2 className="h-4 w-4" /> Terminate</button>
                          </div>
                        )}
                      </div>
                    </td>
                  </tr>
                ))}
                {filteredAdmins.length === 0 && (
                  <tr><td colSpan={9} className="px-4 py-12 text-center text-slate-400">No admins found.</td></tr>
                )}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {showForm && (
        <AdminFormDialog
          admin={selectedAdmin}
          roles={roles || []}
          onClose={() => { setShowForm(false); setSelectedAdmin(null); }}
          onSuccess={refetch}
        />
      )}

      {showPermissions && selectedAdmin && (
        <PermissionsDialog
          admin={selectedAdmin}
          roles={roles || []}
          onClose={() => { setShowPermissions(false); setSelectedAdmin(null); }}
          onSuccess={refetch}
        />
      )}

      {auditAdmin && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4" onClick={() => setAuditAdmin(null)}>
          <div className="w-full max-w-2xl rounded-xl border border-white/10 bg-slate-900 shadow-2xl max-h-[90vh] overflow-y-auto" onClick={(e) => e.stopPropagation()}>
            <div className="flex items-center justify-between border-b border-white/10 p-5">
              <h2 className="text-lg font-semibold text-white">Audit History</h2>
              <button onClick={() => setAuditAdmin(null)} className="rounded-lg p-1 text-slate-400 hover:text-white"><X className="h-5 w-5" /></button>
            </div>
            <div className="p-5">
              <AuditTab adminId={auditAdmin.id} adminName={auditAdmin.name} />
            </div>
          </div>
        </div>
      )}

      {confirmAction && (
        <ConfirmDialog
          title={
            confirmAction.type === 'resetPassword' ? 'Reset Password' :
            confirmAction.type === 'ban' ? 'Ban Admin' :
            confirmAction.type === 'unban' ? 'Unban Admin' :
            confirmAction.type === 'suspend' ? 'Suspend Admin' :
            confirmAction.type === 'activate' ? 'Activate Admin' :
            'Terminate Admin'
          }
          description={
            confirmAction.type === 'resetPassword' ? `Reset password for ${confirmAction.admin.name} (${confirmAction.admin.email})? A temporary password will be set.` :
            confirmAction.type === 'ban' ? `Ban ${confirmAction.admin.name} (${confirmAction.admin.email})? This will prevent the admin from logging in.` :
            confirmAction.type === 'unban' ? `Unban ${confirmAction.admin.name} (${confirmAction.admin.email})? This will restore the admin account.` :
            confirmAction.type === 'suspend' ? `Suspend ${confirmAction.admin.name} (${confirmAction.admin.email})? This will deactivate the admin account.` :
            confirmAction.type === 'activate' ? `Activate ${confirmAction.admin.name} (${confirmAction.admin.email})? This will restore the admin account.` :
            `Permanently terminate ${confirmAction.admin.name} (${confirmAction.admin.email})? This cannot be undone.`
          }
          confirmLabel={
            confirmAction.type === 'resetPassword' ? 'Reset Password' :
            confirmAction.type === 'ban' ? 'Ban' :
            confirmAction.type === 'unban' ? 'Unban' :
            confirmAction.type === 'suspend' ? 'Suspend' :
            confirmAction.type === 'activate' ? 'Activate' :
            'Terminate Permanently'
          }
          confirmVariant={confirmAction.type === 'terminate' || confirmAction.type === 'ban' ? 'danger' : confirmAction.type === 'suspend' ? 'warning' : 'primary'}
          onConfirm={handleAction}
          onClose={() => setConfirmAction(null)}
          loading={confirmLoading}
          extraField={confirmAction.type === 'resetPassword' ? 'password' : undefined}
          extraFieldLabel={confirmAction.type === 'resetPassword' ? 'New Temporary Password' : undefined}
          extraFieldPlaceholder={confirmAction.type === 'resetPassword' ? 'Enter new password' : undefined}
        />
      )}

      {actionMenu && <div className="fixed inset-0 z-10" onClick={() => setActionMenu(null)} />}
    </div>
  );
}
