'use client';

import { useState, useEffect, useCallback } from 'react';
import { adminService } from '@/services/admin.service';
import type { SuperAdminInfo } from '@/types/admin.types';
import { cn, formatDateTime } from '@/lib/utils';
import { usePriorityData } from '@/hooks/usePriorityData';
import { TableSkeleton } from '@/components/priority/skeletons';
import { useAuthStore } from '@/store/auth.store';
import { getErrorMessage } from '@/lib/errors';
import {
  Search, Plus, Pencil, ShieldOff, Shield, Key, X, ChevronDown, ChevronUp,
  Download, FileSpreadsheet, FileText, Loader2, AlertTriangle, Trash2, MoreHorizontal,
  Ban, ShieldCheck, UserCheck
} from 'lucide-react';

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 SuperAdminFormDialog({
  superAdmin, onClose, onSuccess,
}: {
  superAdmin: SuperAdminInfo | null;
  onClose: () => void;
  onSuccess: () => void;
}) {
  const [name, setName] = useState(superAdmin?.name || '');
  const [username, setUsername] = useState(superAdmin?.username || '');
  const [email, setEmail] = useState(superAdmin?.email || '');
  const [phone, setPhone] = useState(superAdmin?.phone || '');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const isEdit = !!superAdmin;

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setLoading(true);
    try {
      if (isEdit) {
        await adminService.updateSuperAdmin(superAdmin.id, { name, email, phone });
      } else {
        if (!password) { setError('Password is required'); setLoading(false); return; }
        await adminService.createSuperAdmin({ name, username, email, password, phone });
      }
      onSuccess();
      onClose();
    } catch (err: any) {
      setError(err?.message || `Failed to ${isEdit ? 'update' : 'create'} super 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 Super Admin' : 'Create Super 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="superadmin_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="superadmin@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>
          {!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 Super Admin' : 'Create Super Admin')}</button>
          </div>
        </form>
      </div>
    </div>
  );
}

function ChangePasswordDialog({
  superAdmin, onClose, onSuccess,
}: {
  superAdmin: SuperAdminInfo;
  onClose: () => void;
  onSuccess: () => void;
}) {
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleChange = async () => {
    setError(null);
    setLoading(true);
    try {
      await adminService.changeSuperAdminPassword(superAdmin.id, { currentPassword, newPassword });
      onSuccess();
      onClose();
    } catch (err: any) {
      setError(getErrorMessage(err));
    } 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-md rounded-xl border border-white/10 bg-slate-900 p-6 shadow-2xl" onClick={(e) => e.stopPropagation()}>
        <h2 className="text-lg font-semibold text-white">Change Password</h2>
        <p className="mt-1 text-sm text-slate-400">
          Change password for <strong className="text-white">{superAdmin.name}</strong> ({superAdmin.email}).
        </p>

        <div className="mt-4 space-y-3">
          <div>
            <label className="mb-1 block text-sm font-medium text-slate-300">Current Password <span className="text-red-400">*</span></label>
            <input
              type="password"
              value={currentPassword}
              onChange={(e) => setCurrentPassword(e.target.value)}
              placeholder="Enter current 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>
            <label className="mb-1 block text-sm font-medium text-slate-300">New Password <span className="text-red-400">*</span></label>
            <input
              type="password"
              value={newPassword}
              onChange={(e) => setNewPassword(e.target.value)}
              placeholder="Enter new 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>
          {error && (
            <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-400">
              {error}
            </div>
          )}
        </div>

        <div className="mt-6 flex justify-end gap-3">
          <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={handleChange}
            disabled={loading || !currentPassword || !newPassword}
            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" /> : 'Change Password'}
          </button>
        </div>
      </div>
    </div>
  );
}

function TerminateDialog({
  superAdmin,
  onClose,
  onSuccess,
}: {
  superAdmin: SuperAdminInfo;
  onClose: () => void;
  onSuccess: () => void;
}) {
  const [password, setPassword] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  const handleTerminate = async () => {
    setError(null);
    setLoading(true);
    try {
      await adminService.terminateSuperAdmin(superAdmin.id, password);
      onSuccess();
      onClose();
    } catch (err: any) {
      setError(getErrorMessage(err));
    } 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-md rounded-xl border border-white/10 bg-slate-900 p-6 shadow-2xl" onClick={(e) => e.stopPropagation()}>
        <h2 className="text-xl font-bold text-white">Terminate Super Admin</h2>
        <p className="mt-2 text-sm text-slate-400">
          You are about to permanently terminate <strong className="text-white">{superAdmin.name}</strong> ({superAdmin.email}).
          This action cannot be undone.
        </p>

        <div className="mt-4 space-y-2">
          <label className="block text-sm font-medium text-slate-300">
            Termination Password
          </label>
          <input
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            placeholder="Enter termination 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"
          />
          <p className="text-xs text-slate-500">Hint: 9034</p>
        </div>

        {error && (
          <div className="mt-3 rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-400">
            {error}
          </div>
        )}

        <div className="mt-6 flex justify-end gap-3">
          <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={handleTerminate}
            disabled={loading || !password}
            className="rounded-lg bg-red-600 px-4 py-2 text-sm font-semibold text-white hover:bg-red-700 disabled:opacity-50"
          >
            {loading ? 'Terminating...' : 'Terminate Permanently'}
          </button>
        </div>
      </div>
    </div>
  );
}

function downloadBlob(blob: Blob, filename: string) {
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}

export default function SuperAdminSuperAdminsPage() {
  const [search, setSearch] = useState('');
  const [selectedSuperAdmin, setSelectedSuperAdmin] = useState<SuperAdminInfo | null>(null);
  const [terminateTarget, setTerminateTarget] = useState<SuperAdminInfo | null>(null);
  const [changePasswordTarget, setChangePasswordTarget] = useState<SuperAdminInfo | null>(null);
  const [confirmAction, setConfirmAction] = useState<{ type: string; superAdmin: SuperAdminInfo } | null>(null);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [showForm, setShowForm] = useState(false);
  const [actionMenu, setActionMenu] = useState<string | null>(null);
  const [exportLoading, setExportLoading] = useState<string | null>(null);

  const currentUserId = (useAuthStore.getState().user?.id as string | undefined);

  const { data: superAdmins = [], loading, error, refetch } = usePriorityData<SuperAdminInfo[]>({
    key: `super-admins:${search}`,
    fetcher: () => adminService.listSuperAdmins({ search, page: 1, limit: 50 }).then(r => r.data || []),
    priority: 'high',
    ttl: 30_000,
  });

  const handleConfirmAction = async (reason: string) => {
    if (!confirmAction) return;
    setConfirmLoading(true);
    try {
      switch (confirmAction.type) {
        case 'suspend':
          await adminService.suspendSuperAdmin(confirmAction.superAdmin.id, reason);
          break;
        case 'activate':
          await adminService.activateSuperAdmin(confirmAction.superAdmin.id);
          break;
        case 'ban':
          await adminService.banSuperAdmin(confirmAction.superAdmin.id, reason);
          break;
        case 'unban':
          await adminService.unbanSuperAdmin(confirmAction.superAdmin.id, reason);
          break;
      }
      refetch();
    } catch (err: any) {
      console.error(err);
    } finally {
      setConfirmLoading(false);
      setConfirmAction(null);
    }
  };

  const handleExport = async (type: 'excel' | 'pdf') => {
    setExportLoading(type);
    try {
      const response = type === 'excel'
        ? await adminService.exportSuperAdminsExcel()
        : await adminService.exportSuperAdminsPdf();
      const ext = type === 'excel' ? 'xlsx' : 'pdf';
      const filename = response.headers?.['content-disposition']
        ? (response.headers['content-disposition'].match(/filename="?([^";]+)"?/)?.[1] || `super-admins-export.${ext}`)
        : `super-admins-export.${ext}`;
      downloadBlob(response.data, filename);
    } catch (err: any) {
      console.error(err);
    } finally {
      setExportLoading(null);
    }
  };

  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">Super Admins</h1>
          <p className="text-slate-400">Search and manage all super admin accounts.</p>
        </div>
        <div className="flex items-center gap-2">
          <button onClick={() => handleExport('excel')} disabled={exportLoading === 'excel'} className="inline-flex items-center gap-2 rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-sm font-semibold text-slate-300 hover:bg-white/10 disabled:opacity-50">
            {exportLoading === 'excel' ? <Loader2 className="h-4 w-4 animate-spin" /> : <FileSpreadsheet className="h-4 w-4" />}
            Export Excel
          </button>
          <button onClick={() => handleExport('pdf')} disabled={exportLoading === 'pdf'} className="inline-flex items-center gap-2 rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-sm font-semibold text-slate-300 hover:bg-white/10 disabled:opacity-50">
            {exportLoading === 'pdf' ? <Loader2 className="h-4 w-4 animate-spin" /> : <FileText className="h-4 w-4" />}
            Export PDF
          </button>
          <button onClick={() => { setSelectedSuperAdmin(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 Super 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 super admins'}</div>
      )}

      <div className="flex items-center gap-4">
        <div className="relative flex-1 max-w-md">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
          <input
            type="text"
            placeholder="Search super 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>

      {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">Super 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">2FA</th>
                  <th className="px-4 py-3">Last Login</th>
                  <th className="px-4 py-3">Created</th>
                  <th className="px-4 py-3 text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-white/5">
                {(superAdmins || []).map((sa) => (
                  <tr key={sa.id} className={cn(sa.id === currentUserId ? 'bg-blue-500/10' : 'hover:bg-white/5')}>
                    <td className="px-4 py-3 text-white font-mono text-xs">{sa.superAdminId}</td>
                    <td className="px-4 py-3 text-white">
                      {sa.name}
                      {sa.id === currentUserId && <span className="ml-2 rounded-full bg-blue-500/20 px-2 py-0.5 text-xs text-blue-300">(You)</span>}
                    </td>
                    <td className="px-4 py-3 text-slate-300">{sa.username}</td>
                    <td className="px-4 py-3 text-slate-300">{sa.email}</td>
                    <td className="px-4 py-3">
                      {sa.isActive ? (
                        <span className="inline-flex items-center gap-1 rounded-full bg-green-500/20 px-2 py-1 text-xs text-green-300"><Shield 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"><ShieldOff className="h-3 w-3" /> Inactive</span>
                      )}
                    </td>
                    <td className="px-4 py-3 text-slate-300">
                      {sa.twoFactorEnabled ? 'Enabled' : 'Disabled'}
                    </td>
                    <td className="px-4 py-3 text-slate-300">
                      {sa.lastLoginAt ? formatDateTime(sa.lastLoginAt) : 'Never'}
                    </td>
                    <td className="px-4 py-3 text-slate-300">
                      {new Date(sa.createdAt).toLocaleDateString()}
                    </td>
                    <td className="px-4 py-3">
                      <div className="relative flex items-center justify-end">
                        <button onClick={() => setActionMenu(actionMenu === sa.id ? null : sa.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 === sa.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={() => { setSelectedSuperAdmin(sa); 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={() => { setChangePasswordTarget(sa); 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" /> Change Password</button>
                            <div className="my-1 border-t border-white/10" />
                            {sa.status === 'BANNED' ? (
                              <button onClick={() => { setConfirmAction({ type: 'activate', superAdmin: sa }); setActionMenu(null); }} className="flex w-full items-center gap-2 px-4 py-2 text-sm text-green-400 hover:bg-white/5"><Shield className="h-4 w-4" /> Activate</button>
                            ) : sa.isActive ? (
                              <button onClick={() => { setConfirmAction({ type: 'suspend', superAdmin: sa }); 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: 'activate', superAdmin: sa }); setActionMenu(null); }} className="flex w-full items-center gap-2 px-4 py-2 text-sm text-green-400 hover:bg-white/5"><Shield className="h-4 w-4" /> Activate</button>
                            )}
                            {sa.status !== 'BANNED' && (
                              <button onClick={() => { setConfirmAction({ type: 'ban', superAdmin: sa }); 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>
                            )}
                            {sa.status === 'BANNED' && (
                              <button onClick={() => { setConfirmAction({ type: 'unban', superAdmin: sa }); 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>
                            )}
                            <button onClick={() => { setTerminateTarget(sa); 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>
                ))}
                {(superAdmins || []).length === 0 && (
                  <tr><td colSpan={9} className="px-4 py-12 text-center text-slate-400">No super admins found.</td></tr>
                )}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {showForm && (
        <SuperAdminFormDialog
          superAdmin={selectedSuperAdmin}
          onClose={() => { setShowForm(false); setSelectedSuperAdmin(null); }}
          onSuccess={refetch}
        />
      )}

      {changePasswordTarget && (
        <ChangePasswordDialog
          superAdmin={changePasswordTarget}
          onClose={() => setChangePasswordTarget(null)}
          onSuccess={refetch}
        />
      )}

      {terminateTarget && (
        <TerminateDialog
          superAdmin={terminateTarget}
          onClose={() => setTerminateTarget(null)}
          onSuccess={refetch}
        />
      )}

      {confirmAction && (
        <ConfirmDialog
          title={
            confirmAction.type === 'suspend' ? 'Suspend Super Admin' :
            confirmAction.type === 'activate' ? 'Activate Super Admin' :
            confirmAction.type === 'ban' ? 'Ban Super Admin' :
            confirmAction.type === 'unban' ? 'Unban Super Admin' :
            'Confirm Action'
          }
          description={
            confirmAction.type === 'suspend'
              ? `Suspend ${confirmAction.superAdmin.name} (${confirmAction.superAdmin.email})? This will deactivate the super admin account.`
              : confirmAction.type === 'ban'
                ? `Ban ${confirmAction.superAdmin.name} (${confirmAction.superAdmin.email})? This will prevent the super admin from logging in.`
                : confirmAction.type === 'unban'
                  ? `Unban ${confirmAction.superAdmin.name} (${confirmAction.superAdmin.email})? This will restore the super admin account.`
                  : `Activate ${confirmAction.superAdmin.name} (${confirmAction.superAdmin.email})? This will restore the super admin account.`
          }
          confirmLabel={
            confirmAction.type === 'suspend' ? 'Suspend' :
            confirmAction.type === 'ban' ? 'Ban' :
            confirmAction.type === 'unban' ? 'Unban' :
            'Activate'
          }
          confirmVariant={confirmAction.type === 'ban' || confirmAction.type === 'suspend' ? 'warning' : 'primary'}
          onConfirm={handleConfirmAction}
          onClose={() => setConfirmAction(null)}
          loading={confirmLoading}
        />
      )}

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