'use client';

import { useState, useEffect, useCallback } from 'react';
import { adminService } from '@/services/admin.service';
import type { AxiosResponse } from 'axios';
import type { UserProfile, UserDetailInfo, AdjustUserBalancePayload, LoginHistoryEntry, TransactionEntry, UserReferralInfo, UserSecurityInfo, RoleInfo } from '@/types/admin.types';
import { cn, formatDateTime, formatCurrency } from '@/lib/utils';
import { getErrorMessage } from '@/lib/errors';
import { safeArray } from '@/lib/safe-array';
import { usePriorityData } from '@/hooks/usePriorityData';
import { TableSkeleton } from '@/components/priority/skeletons';
import EmptyState from '@/components/EmptyState';
import { saveAs } from 'file-saver';
import { Tooltip } from '@/components/ui/tooltip';
import {
  Search, X, Download, ChevronDown, ChevronUp, Loader2, CheckCircle2, XCircle,
  AlertCircle, UserPlus, Ban, CheckSquare, XSquare, RefreshCw,
  Wallet, CreditCard, Activity, Clock, Users, Shield, FileText, Eye,
  Plus, Trash2, Pencil, UserCheck, UserX, AlertTriangle, Key,
  ChevronLeft, ChevronRight, ClipboardList, Filter,
  Settings, Lock, Unlock, DollarSign, History, ShieldCheck,
} from 'lucide-react';

type Tab = 'profile' | 'wallet' | 'transactions' | 'loginHistory' | 'referrals' | 'security';

const downloadBlob = (blob: Blob, filename: string) => {
  saveAs(blob, filename);
};

function _extractFilename(response: AxiosResponse<Blob>, fallback: string): string {
  const disposition = response.headers['content-disposition'] as string | undefined;
  if (disposition) {
    const utf8 = disposition.match(/filename\*=UTF-8''([^;]+)/i);
    if (utf8) return decodeURIComponent(utf8[1]);
    const m = disposition.match(/filename="?([^";]+)"?/i);
    if (m) return decodeURIComponent(m[1]);
  }
  return fallback;
}

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

  const handleConfirm = () => {
    if (!reason.trim()) return;
    if (extraField && !extra.trim()) return;
    onConfirm(reason.trim(), extra.trim() || undefined);
  };

  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>
          {confirmTooltip ? (
            <Tooltip content={confirmTooltip}>
              <button
                onClick={handleConfirm}
                disabled={Boolean(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>
            </Tooltip>
          ) : (
            <button
              onClick={handleConfirm}
              disabled={Boolean(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 UserDetailModal({
  user, onClose, onRefresh,
}: {
  user: UserProfile;
  onClose: () => void;
  onRefresh: () => void;
}) {
  const [activeTab, setActiveTab] = useState<Tab>('profile');
  const [detail, setDetail] = useState<UserDetailInfo | null>(null);
  const [transactions, setTransactions] = useState<TransactionEntry[]>([]);
  const [loginHistory, setLoginHistory] = useState<LoginHistoryEntry[]>([]);
  const [referrals, setReferrals] = useState<UserReferralInfo[]>([]);
  const [security, setSecurity] = useState<UserSecurityInfo | null>(null);
  const [loadingDetail, setLoadingDetail] = useState(false);
  const [actionLoading, setActionLoading] = useState(false);
  const [actionError, setActionError] = useState<string | null>(null);

  const [confirmAction, setConfirmAction] = useState<{ type: 'ban' | 'freeze' | 'suspend' | 'activate' | 'terminate'; user: UserProfile } | null>(null);

  const [adjMode, setAdjMode] = useState<'SET' | 'ADD' | 'SUBTRACT'>('ADD');
  const [adjTarget, setAdjTarget] = useState<'balance' | 'locked' | 'pending'>('balance');
  const [adjAmount, setAdjAmount] = useState('');
  const [adjNewBalance, setAdjNewBalance] = useState('');
  const [adjNewLocked, setAdjNewLocked] = useState('');
  const [adjNewPending, setAdjNewPending] = useState('');
  const [adjReason, setAdjReason] = useState('');
  const [adjLoading, setAdjLoading] = useState(false);
  const [adjError, setAdjError] = useState<string | null>(null);
  const [adjSuccess, setAdjSuccess] = useState(false);

  const [showFineForm, setShowFineForm] = useState(false);
  const [fineAmount, setFineAmount] = useState('');
  const [fineReason, setFineReason] = useState('');
  const [fineEffectiveDate, setFineEffectiveDate] = useState('');
  const [fineExpiryDate, setFineExpiryDate] = useState('');
  const [fineLoading, setFineLoading] = useState(false);
  const [fineError, setFineError] = useState<string | null>(null);
  const [fineSuccess, setFineSuccess] = useState(false);

  const loadDetail = useCallback(async () => {
    setLoadingDetail(true);
    try {
      const results = await Promise.allSettled([
        adminService.getUserDetail(user.id),
        adminService.getUserTransactions(user.id, 1, 20),
        adminService.getUserLoginHistory(user.id, 1, 20),
        adminService.getUserReferrals(user.id),
        adminService.getUserSecurity(user.id),
      ]);
      const [d, tx, lh, ref, sec] = results;
      if (d.status === 'fulfilled') setDetail(d.value);
      else setActionError(`Profile: ${getErrorMessage(d.reason)}`);
      if (tx.status === 'fulfilled') setTransactions(safeArray<TransactionEntry>((tx.value as any)?.data || tx.value));
      if (lh.status === 'fulfilled') setLoginHistory(safeArray<LoginHistoryEntry>((lh.value as any)?.data || lh.value));
      if (ref.status === 'fulfilled') setReferrals(safeArray<UserReferralInfo>(ref.value));
      if (sec.status === 'fulfilled') setSecurity(sec.value);
    } catch (err: any) {
      setActionError(getErrorMessage(err));
    } finally {
      setLoadingDetail(false);
    }
  }, [user.id]);

  useEffect(() => {
    if (activeTab === 'profile' || activeTab === 'wallet') {
      if (!detail) loadDetail();
    }
    if (activeTab === 'transactions' && transactions.length === 0) loadDetail();
    if (activeTab === 'loginHistory' && loginHistory.length === 0) loadDetail();
    if (activeTab === 'referrals' && referrals.length === 0) loadDetail();
    if (activeTab === 'security' && !security) loadDetail();
  }, [activeTab]);

  const parseDateToIso = (dateStr: string): string => {
    if (!dateStr) return '';
    // Handle YYYY-MM-DD format (standard HTML date input)
    if (/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
      return new Date(dateStr + 'T00:00:00.000Z').toISOString();
    }
    // Handle DD-MM-YYYY format
    if (/^\d{2}-\d{2}-\d{4}$/.test(dateStr)) {
      const [day, month, year] = dateStr.split('-');
      return new Date(`${year}-${month}-${day}T00:00:00.000Z`).toISOString();
    }
    // Try parsing as-is
    const parsed = new Date(dateStr);
    return isNaN(parsed.getTime()) ? '' : parsed.toISOString();
  };

  const handleAdjustBalance = async () => {
    setAdjError(null);
    setAdjSuccess(false);
    if (adjReason.trim().length < 5) {
      setAdjError('Reason must be at least 5 characters');
      return;
    }
    setAdjLoading(true);
    try {
      const payload: AdjustUserBalancePayload = {
        userId: user.id,
        mode: adjMode,
        target: adjTarget,
        reason: adjReason.trim(),
      };
      if (adjMode === 'SET') {
        if (adjTarget === 'balance' && adjNewBalance !== '') payload.newBalance = parseFloat(adjNewBalance);
        if (adjTarget === 'locked' && adjNewLocked !== '') payload.newLocked = parseFloat(adjNewLocked);
        if (adjTarget === 'pending' && adjNewPending !== '') payload.newPending = parseFloat(adjNewPending);
      } else {
        if (adjAmount === '') {
          setAdjError('Amount is required');
          setAdjLoading(false);
          return;
        }
        payload.amount = parseFloat(adjAmount);
      }
      const updated = await adminService.adjustUserBalance(payload);
      setDetail((prev) => prev ? { ...prev, wallet: updated as any } : null);
      setAdjSuccess(true);
      setAdjAmount('');
      setAdjNewBalance('');
      setAdjNewLocked('');
      setAdjNewPending('');
      setAdjReason('');
      onRefresh();
    } catch (err: any) {
      setAdjError(getErrorMessage(err));
    } finally {
      setAdjLoading(false);
    }
  };

  const handleApplyFine = async () => {
    setFineError(null);
    setFineSuccess(false);
    if (!fineAmount || parseFloat(fineAmount) <= 0) {
      setFineError('Valid fine amount is required');
      return;
    }
    if (!fineReason.trim() || fineReason.trim().length < 5) {
      setFineError('Reason must be at least 5 characters');
      return;
    }
    if (!fineEffectiveDate) {
      setFineError('Effective date is required');
      return;
    }
    setFineLoading(true);
    try {
      const effectiveDateIso = parseDateToIso(fineEffectiveDate);
      const expiryDateIso = fineExpiryDate ? parseDateToIso(fineExpiryDate) : new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toISOString();

      if (!effectiveDateIso) {
        setFineError('Invalid effective date format');
        return;
      }

      await adminService.createFine({
        userId: user.id,
        amount: parseFloat(fineAmount),
        reason: fineReason.trim(),
        effectiveDate: effectiveDateIso,
        expiryDate: expiryDateIso,
      });
      setFineSuccess(true);
      setFineAmount('');
      setFineReason('');
      setFineEffectiveDate('');
      setFineExpiryDate('');
      setShowFineForm(false);
      onRefresh();
    } catch (err: any) {
      setFineError(getErrorMessage(err));
    } finally {
      setFineLoading(false);
    }
  };

  const handleConfirmAction = async (reason: string, extra?: string) => {
    if (!confirmAction) return;
    setActionLoading(true);
    setActionError(null);
    try {
      const targetUserId = confirmAction.user.id;
      if (confirmAction.type === 'ban') {
        await adminService.banUserBySuperAdmin(targetUserId, reason, extra);
      } else if (confirmAction.type === 'freeze') {
        await adminService.freezeUserWalletBySuperAdmin(targetUserId, reason, extra);
      } else if (confirmAction.type === 'suspend') {
        await adminService.suspendUser(targetUserId, reason, extra);
      } else if (confirmAction.type === 'activate') {
        await adminService.activateUser(targetUserId, reason || undefined);
      } else if (confirmAction.type === 'terminate') {
        await adminService.terminateUser(targetUserId, reason, extra);
      }
      onRefresh();
      loadDetail();
      setConfirmAction(null);
    } catch (err: any) {
      setActionError(getErrorMessage(err));
    } finally {
      setActionLoading(false);
    }
  };

  const wallet = detail?.wallet || user.wallet;
  const tabs: { key: Tab; label: string; icon: React.ElementType }[] = [
    { key: 'profile', label: 'Profile', icon: Eye },
    { key: 'wallet', label: 'Wallet', icon: Wallet },
    { key: 'transactions', label: 'Transactions', icon: Activity },
    { key: 'loginHistory', label: 'Login History', icon: Clock },
    { key: 'referrals', label: 'Referrals', icon: Users },
    { key: 'security', label: 'Security', icon: Shield },
  ];

  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-4xl rounded-xl border border-white/10 bg-slate-900 shadow-2xl max-h-[90vh] overflow-hidden flex flex-col" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between border-b border-white/10 p-5 shrink-0">
          <div>
            <h2 className="text-lg font-semibold text-white">{user.firstName} {user.lastName}</h2>
            <p className="text-sm text-slate-400">{user.email}</p>
          </div>
          <div className="flex items-center gap-2">
            <Tooltip content="Stop this user from accessing their account. They cannot log in until you unban them.">
              <button
                onClick={() => setConfirmAction({ type: 'ban', user })}
                className="rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-xs font-medium text-red-300 hover:bg-red-500/20 flex items-center gap-1.5"
              >
                <Ban className="h-4 w-4" /> Ban
              </button>
            </Tooltip>
            <Tooltip content="Block all money transactions for this user. They cannot send or receive money.">
              <button
                onClick={() => setConfirmAction({ type: 'freeze', user })}
                className="rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs font-medium text-amber-300 hover:bg-amber-500/20 flex items-center gap-1.5"
              >
                <Lock className="h-4 w-4" /> Freeze
              </button>
            </Tooltip>
            <Tooltip content="Temporarily stop this user from using the platform. They can be activated later.">
              <button
                onClick={() => setConfirmAction({ type: 'suspend', user })}
                className="rounded-lg border border-orange-500/30 bg-orange-500/10 px-3 py-2 text-xs font-medium text-orange-300 hover:bg-orange-500/20 flex items-center gap-1.5"
              >
                <UserX className="h-4 w-4" /> Suspend
              </button>
            </Tooltip>
            <Tooltip content="Allow this user to use the platform again after being banned or suspended.">
              <button
                onClick={() => setConfirmAction({ type: 'activate', user })}
                className="rounded-lg border border-green-500/30 bg-green-500/10 px-3 py-2 text-xs font-medium text-green-300 hover:bg-green-500/20 flex items-center gap-1.5"
              >
                <CheckSquare className="h-4 w-4" /> Activate
              </button>
            </Tooltip>
            <Tooltip content="PERMANENTLY DELETE this user and ALL their data. This cannot be undone. Use with extreme caution.">
              <button
                onClick={() => setConfirmAction({ type: 'terminate', user })}
                className="rounded-lg border border-red-600/40 bg-red-600/15 px-3 py-2 text-xs font-medium text-red-200 hover:bg-red-600/25 flex items-center gap-1.5"
              >
                <Trash2 className="h-4 w-4" /> Terminate
              </button>
            </Tooltip>
            <button
              onClick={() => setShowFineForm(!showFineForm)}
              className="rounded-lg border border-amber-600/40 bg-amber-600/15 px-3 py-2 text-xs font-medium text-amber-200 hover:bg-amber-600/25 flex items-center gap-1.5"
            >
              <AlertTriangle className="h-4 w-4" /> Apply Fine
            </button>
            <button onClick={onClose} className="rounded-lg p-1 text-slate-400 hover:text-white">
              <X className="h-5 w-5" />
            </button>
          </div>
        </div>

        <div className="flex shrink-0 border-b border-white/10 overflow-x-auto">
          {tabs.map((tab) => {
            const Icon = tab.icon;
            return (
              <button
                key={tab.key}
                onClick={() => setActiveTab(tab.key)}
                className={cn(
                  'flex items-center gap-2 px-4 py-3 text-sm font-medium whitespace-nowrap border-b-2 transition-colors',
                  activeTab === tab.key
                    ? 'border-blue-500 text-blue-300'
                    : 'border-transparent text-slate-400 hover:text-white',
                )}
              >
                <Icon className="h-4 w-4" /> {tab.label}
              </button>
            );
          })}
        </div>

        <div className="flex-1 overflow-y-auto p-5 space-y-5">
          {actionError && (
            <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-400">{actionError}</div>
          )}
          {loadingDetail && (
            <div className="flex items-center justify-center py-8 text-slate-400">
              <Loader2 className="h-6 w-6 animate-spin mr-2" /> Loading...
            </div>
          )}

          {activeTab === 'profile' && detail && (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <ProfileField label="Email" value={detail.email} />
              <ProfileField label="Name" value={`${detail.firstName || ''} ${detail.lastName || ''}`.trim() || 'N/A'} />
              <ProfileField label="Phone" value={detail.phone || 'N/A'} />
              <ProfileField label="Income Range" value={detail.incomeRange || 'N/A'} />
              <ProfileField label="Min Buy" value={detail.minBuyAmount != null ? `$${detail.minBuyAmount.toFixed(2)}` : 'N/A'} />
              <ProfileField label="Role" value={detail.role?.name || 'N/A'} />
              <ProfileField label="Status" value={detail.isBanned ? 'Banned' : detail.isDisabled ? 'Disabled' : 'Active'} />
              <ProfileField label="KYC Verified" value={detail.isKycVerified ? 'Verified' : 'Pending'} />
              <ProfileField label="Email Verified" value={detail.isEmailVerified ? 'Yes' : 'No'} />
              <ProfileField label="Phone Verified" value={detail.isPhoneVerified ? 'Yes' : 'No'} />
              <ProfileField label="Two-Factor" value={detail.isTwoFactorEnabled ? 'Enabled' : 'Disabled'} />
              <ProfileField label="Last Login" value={detail.lastLoginAt ? formatDateTime(detail.lastLoginAt) : 'N/A'} />
              <ProfileField label="Last Login IP" value={detail.lastLoginIp || 'N/A'} />
              <ProfileField label="Joined" value={formatDateTime(detail.createdAt)} />
            </div>
          )}

          {activeTab === 'wallet' && wallet && (
            <div className="space-y-5">
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                <WalletCard label="Available" value={Number(wallet.balance).toFixed(2)} icon={Wallet} />
                <WalletCard label="Locked" value={Number(wallet.locked).toFixed(2)} icon={Lock} />
                <WalletCard label="Pending" value={Number(wallet.pendingBalance || '0').toFixed(2)} icon={CreditCard} />
                <WalletCard label="Frozen" value={wallet.isFrozen ? 'Yes' : 'No'} icon={wallet.isFrozen ? Unlock : Lock} color={wallet.isFrozen ? 'text-red-400' : 'text-green-400'} />
              </div>

              <div className="rounded-xl border border-white/10 bg-white/5 p-5">
                <h3 className="text-sm font-semibold text-white mb-4 flex items-center gap-2">
                  <DollarSign className="h-4 w-4" /> Balance Adjustment
                </h3>
                {adjError && <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-400 mb-4">{adjError}</div>}
                {adjSuccess && (
                  <div className="rounded-lg border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-400 mb-4 flex items-center gap-2">
                    <CheckCircle2 className="h-4 w-4" /> Balance adjusted successfully
                  </div>
                )}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <label className="mb-1 block text-sm font-medium text-slate-300">Mode</label>
                    <select value={adjMode} onChange={(e) => setAdjMode(e.target.value as 'SET' | 'ADD' | 'SUBTRACT')} 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="ADD">ADD</option>
                      <option value="SUBTRACT">SUBTRACT</option>
                      <option value="SET">SET</option>
                    </select>
                  </div>
                  <div>
                    <label className="mb-1 block text-sm font-medium text-slate-300">Target</label>
                    <select value={adjTarget} onChange={(e) => setAdjTarget(e.target.value as 'balance' | 'locked' | 'pending')} 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="balance">Balance</option>
                      <option value="locked">Locked</option>
                      <option value="pending">Pending</option>
                    </select>
                  </div>
                  {adjMode === 'SET' ? (
                    <>
                      {adjTarget === 'balance' && (
                        <div>
                          <label className="mb-1 block text-sm font-medium text-slate-300">New Balance</label>
                          <input type="number" step="0.00000001" value={adjNewBalance} onChange={(e) => setAdjNewBalance(e.target.value)} placeholder="0.00" 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>
                      )}
                      {adjTarget === 'locked' && (
                        <div>
                          <label className="mb-1 block text-sm font-medium text-slate-300">New Locked</label>
                          <input type="number" step="0.00000001" value={adjNewLocked} onChange={(e) => setAdjNewLocked(e.target.value)} placeholder="0.00" 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>
                      )}
                      {adjTarget === 'pending' && (
                        <div>
                          <label className="mb-1 block text-sm font-medium text-slate-300">New Pending</label>
                          <input type="number" step="0.00000001" value={adjNewPending} onChange={(e) => setAdjNewPending(e.target.value)} placeholder="0.00" 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">Amount</label>
                      <input type="number" step="0.00000001" value={adjAmount} onChange={(e) => setAdjAmount(e.target.value)} placeholder="0.00" 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={cn(adjMode === 'SET' ? 'md:col-span-2' : 'md:col-span-2')}>
                    <label className="mb-1 block text-sm font-medium text-slate-300">Reason <span className="text-red-400">*</span></label>
                    <textarea
                      value={adjReason}
                      onChange={(e) => setAdjReason(e.target.value)}
                      placeholder="Reason for adjustment (min 5 characters)"
                      rows={3}
                      minLength={5}
                      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>
                </div>
                <div className="mt-4 flex justify-end">
                  <button
                    onClick={handleAdjustBalance}
                    disabled={adjLoading}
                    className="rounded-lg bg-blue-600 px-4 py-2 text-sm font-semibold text-white hover:bg-blue-700 disabled:opacity-50 flex items-center gap-2"
                  >
                    {adjLoading ? <Loader2 className="h-4 w-4 animate-spin" /> : <DollarSign className="h-4 w-4" />} Submit Adjustment
                  </button>
                </div>
              </div>

              {showFineForm && (
                <div className="rounded-xl border border-amber-500/30 bg-amber-500/5 p-5">
                  <h3 className="text-sm font-semibold text-white mb-4 flex items-center gap-2">
                    <AlertTriangle className="h-4 w-4 text-amber-400" /> Apply Fine
                  </h3>
                  {fineError && <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-400 mb-4">{fineError}</div>}
                  {fineSuccess && (
                    <div className="rounded-lg border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-400 mb-4 flex items-center gap-2">
                      <CheckCircle2 className="h-4 w-4" /> Fine applied successfully
                    </div>
                  )}
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <label className="mb-1 block text-sm font-medium text-slate-300">Fine Amount (USDT) <span className="text-red-400">*</span></label>
                      <input type="number" step="0.01" min="0" value={fineAmount} onChange={(e) => setFineAmount(e.target.value)} placeholder="0.00" className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-white placeholder:text-slate-400 focus:border-amber-500 focus:outline-none" />
                    </div>
                    <div>
                      <label className="mb-1 block text-sm font-medium text-slate-300">Effective Date <span className="text-red-400">*</span></label>
                      <input type="datetime-local" value={fineEffectiveDate} onChange={(e) => setFineEffectiveDate(e.target.value)} className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-white focus:border-amber-500 focus:outline-none" />
                    </div>
                    <div>
                      <label className="mb-1 block text-sm font-medium text-slate-300">Expiry Date</label>
                      <input type="datetime-local" value={fineExpiryDate} onChange={(e) => setFineExpiryDate(e.target.value)} className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-white focus:border-amber-500 focus:outline-none" />
                      <p className="mt-1 text-xs text-slate-400">Leave empty for no expiry (stays until paid)</p>
                    </div>
                    <div className="md:col-span-2">
                      <label className="mb-1 block text-sm font-medium text-slate-300">Reason <span className="text-red-400">*</span></label>
                      <textarea
                        value={fineReason}
                        onChange={(e) => setFineReason(e.target.value)}
                        placeholder="Reason for applying fine (min 5 characters)"
                        rows={3}
                        minLength={5}
                        className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-white placeholder:text-slate-400 focus:border-amber-500 focus:outline-none resize-none"
                      />
                    </div>
                  </div>
                  <div className="mt-4 flex justify-end gap-3">
                    <button
                      onClick={() => setShowFineForm(false)}
                      className="rounded-lg border border-white/10 px-4 py-2 text-sm text-slate-300 hover:bg-white/5"
                    >
                      Cancel
                    </button>
                    <button
                      onClick={handleApplyFine}
                      disabled={fineLoading}
                      className="rounded-lg bg-amber-600 px-4 py-2 text-sm font-semibold text-white hover:bg-amber-700 disabled:opacity-50 flex items-center gap-2"
                    >
                      {fineLoading ? <Loader2 className="h-4 w-4 animate-spin" /> : <AlertTriangle className="h-4 w-4" />} Apply Fine
                    </button>
                  </div>
                </div>
              )}
            </div>
          )}

          {activeTab === 'transactions' && (
            <div className="rounded-xl border border-white/10 overflow-hidden">
              <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">Date</th>
                    <th className="px-4 py-3">Type</th>
                    <th className="px-4 py-3">Amount</th>
                    <th className="px-4 py-3">Balance Before</th>
                    <th className="px-4 py-3">Balance After</th>
                    <th className="px-4 py-3">Description</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-white/5">
                  {(transactions ?? []).map((tx) => (
                    <tr key={tx.id} className="hover:bg-white/5">
                      <td className="px-4 py-3 text-slate-300 whitespace-nowrap">{formatDateTime(tx.createdAt)}</td>
                      <td className="px-4 py-3">
                        <span className={cn(
                          'rounded-full px-2 py-1 text-xs font-medium',
                          tx.type === 'CREDIT' ? 'bg-green-500/20 text-green-300' : 'bg-red-500/20 text-red-300',
                        )}>{tx.type}</span>
                      </td>
                      <td className="px-4 py-3 text-white font-medium">{formatCurrency(tx.amount)}</td>
                      <td className="px-4 py-3 text-slate-300">{tx.balanceBefore ? formatCurrency(tx.balanceBefore) : '—'}</td>
                      <td className="px-4 py-3 text-slate-300">{tx.balanceAfter ? formatCurrency(tx.balanceAfter) : '—'}</td>
                      <td className="px-4 py-3 text-slate-300">{tx.description || '—'}</td>
                    </tr>
                  ))}
                  {transactions.length === 0 && (
                    <tr><td colSpan={6} className="px-4 py-8 text-center text-slate-400">No transactions found.</td></tr>
                  )}
                </tbody>
              </table>
            </div>
          )}

          {activeTab === 'loginHistory' && (
            <div className="rounded-xl border border-white/10 overflow-hidden">
              <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">Date</th>
                    <th className="px-4 py-3">IP</th>
                    <th className="px-4 py-3">Method</th>
                    <th className="px-4 py-3">Status</th>
                    <th className="px-4 py-3">Device</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-white/5">
                  {(loginHistory ?? []).map((entry) => (
                    <tr key={entry.id} className="hover:bg-white/5">
                      <td className="px-4 py-3 text-slate-300 whitespace-nowrap">{formatDateTime(entry.createdAt)}</td>
                      <td className="px-4 py-3 text-slate-300">{entry.ipAddress || 'N/A'}</td>
                      <td className="px-4 py-3 text-slate-300">{entry.loginMethod}</td>
                      <td className="px-4 py-3">
                        {entry.isSuccess ? (
                          <span className="rounded-full bg-green-500/20 px-2 py-1 text-xs text-green-300">Success</span>
                        ) : (
                          <span className="rounded-full bg-red-500/20 px-2 py-1 text-xs text-red-300">Failed</span>
                        )}
                      </td>
                      <td className="px-4 py-3 text-slate-300">
                        {entry.device ? `${entry.device.browser || 'N/A'} / ${entry.device.operatingSystem || 'N/A'}` : 'N/A'}
                      </td>
                    </tr>
                  ))}
                  {loginHistory.length === 0 && (
                    <tr><td colSpan={5} className="px-4 py-8 text-center text-slate-400">No login history found.</td></tr>
                  )}
                </tbody>
              </table>
            </div>
          )}

          {activeTab === 'referrals' && (
            <div className="rounded-xl border border-white/10 overflow-hidden">
              <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">Referred By</th>
                    <th className="px-4 py-3">Referred User</th>
                    <th className="px-4 py-3">Code</th>
                    <th className="px-4 py-3">Reward</th>
                    <th className="px-4 py-3">Status</th>
                    <th className="px-4 py-3">Date</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-white/5">
                   {(referrals ?? []).map((ref) => (
                    <tr key={ref.id} className="hover:bg-white/5">
                      <td className="px-4 py-3 text-slate-300">{ref.referrer?.email || 'N/A'}</td>
                      <td className="px-4 py-3 text-slate-300">{ref.referred?.email || 'N/A'}</td>
                      <td className="px-4 py-3 text-slate-300">{ref.referralCode || 'N/A'}</td>
                      <td className="px-4 py-3 text-white">{ref.reward ? formatCurrency(ref.reward) : '—'}</td>
                      <td className="px-4 py-3">
                        <span className={cn(
                          'rounded-full px-2 py-1 text-xs',
                          ref.status === 'COMPLETED' ? 'bg-green-500/20 text-green-300' : 'bg-amber-500/20 text-amber-300',
                        )}>{ref.status}</span>
                      </td>
                      <td className="px-4 py-3 text-slate-300">{formatDateTime(ref.createdAt)}</td>
                    </tr>
                  ))}
                  {referrals.length === 0 && (
                    <tr><td colSpan={6} className="px-4 py-8 text-center text-slate-400">No referrals found.</td></tr>
                  )}
                </tbody>
              </table>
            </div>
          )}

          {activeTab === 'security' && security && (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <ProfileField label="Two-Factor" value={security.isTwoFactorEnabled ? `Enabled (${security.twoFactorType || 'N/A'})` : 'Disabled'} />
              <ProfileField label="Email Verified" value={security.emailVerified ? 'Yes' : 'No'} />
              <ProfileField label="Phone Verified" value={security.phoneVerified ? 'Yes' : 'No'} />
              <ProfileField label="Failed Attempts" value={String(security.failedLoginAttempts)} />
              <ProfileField label="Locked Until" value={security.lockedUntil ? formatDateTime(security.lockedUntil) : 'N/A'} />
              <div className="md:col-span-2">
                <h4 className="text-sm font-medium text-slate-300 mb-2">Devices</h4>
                    {security && security.devices && security.devices.length > 0 ? (
                      <div className="space-y-2">
                        {(security.devices ?? []).map((device) => (
                      <div key={device.id} className="rounded-lg border border-white/10 bg-white/5 p-3 text-sm text-slate-300 flex items-center gap-2">
                        <ShieldCheck className="h-4 w-4 text-blue-400" />
                        {device.deviceName || 'Unknown'} - {device.deviceType || 'N/A'} / {device.browser || 'N/A'} / {device.operatingSystem || 'N/A'}
                        <span className="text-slate-500 ml-auto text-xs">{device.lastUsedAt ? formatDateTime(device.lastUsedAt) : ''}</span>
                      </div>
                    ))}
                  </div>
                ) : (
                  <p className="text-sm text-slate-500">No devices found.</p>
                )}
              </div>
            </div>
          )}
        </div>
      </div>

      {confirmAction && (
        <ConfirmDialog
          title={confirmAction.type === 'suspend' ? 'Suspend User' : confirmAction.type === 'activate' ? 'Activate User' : 'Terminate User'}
          description={
            confirmAction.type === 'suspend'
              ? 'This will suspend the user account. Provide a reason below.'
              : confirmAction.type === 'activate'
              ? 'This will reactivate the user account. Provide a reason below.'
              : 'This will permanently terminate the user account. This action cannot be undone.'
          }
          confirmLabel={confirmAction.type === 'suspend' ? 'Suspend' : confirmAction.type === 'activate' ? 'Activate' : 'Terminate'}
          confirmVariant={confirmAction.type === 'terminate' ? 'danger' : confirmAction.type === 'suspend' ? 'warning' : 'primary'}
          onConfirm={handleConfirmAction}
          onClose={() => setConfirmAction(null)}
          loading={actionLoading}
          extraField={confirmAction.type === 'terminate' ? 'password' : undefined}
          extraFieldLabel={confirmAction.type === 'terminate' ? 'Admin Password (for audit)' : undefined}
          extraFieldPlaceholder={confirmAction.type === 'terminate' ? 'Enter your password' : undefined}
          confirmTooltip={
            confirmAction.type === 'ban' ? 'Stop this user from accessing their account. They cannot log in until you unban them.' :
            confirmAction.type === 'freeze' ? 'Block all money transactions for this user. They cannot send or receive money.' :
            confirmAction.type === 'suspend' ? 'Temporarily stop this user from using the platform. They can be activated later.' :
            confirmAction.type === 'activate' ? 'Allow this user to use the platform again after being banned or suspended.' :
            confirmAction.type === 'terminate' ? 'PERMANENTLY DELETE this user and ALL their data. This cannot be undone. Use with extreme caution.' :
            undefined
          }
        />
      )}
    </div>
  );
}

function ProfileField({ label, value }: { label: string; value: string }) {
  return (
    <div className="rounded-lg border border-white/10 bg-white/5 p-3">
      <p className="text-xs font-medium uppercase text-slate-400 mb-1">{label}</p>
      <p className="text-sm text-white">{value}</p>
    </div>
  );
}

function UserFormDialog({ roles, onClose, onSuccess }: { roles: RoleInfo[]; onClose: () => void; onSuccess: () => void }) {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [phone, setPhone] = useState('');
  const [roleId, setRoleId] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    if (!email || !password) {
      setError('Email and password are required');
      return;
    }
    setLoading(true);
    try {
      await adminService.createUser({
        email,
        password,
        firstName: firstName || undefined,
        lastName: lastName || undefined,
        phone: phone || undefined,
        roleId: roleId || undefined,
      });
      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-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">Add User</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>}
          <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="user@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">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="grid grid-cols-2 gap-4">
            <div>
              <label className="mb-1 block text-sm font-medium text-slate-300">First Name</label>
              <input type="text" value={firstName} onChange={(e) => setFirstName(e.target.value)} placeholder="John" 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">Last Name</label>
              <input type="text" value={lastName} onChange={(e) => setLastName(e.target.value)} placeholder="Doe" 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>
            <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>
          <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>
            <Tooltip content="Save the new user account to the system.">
              <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" /> : 'Create User'}</button>
            </Tooltip>
          </div>
        </form>
      </div>
    </div>
  );
}

function WalletCard({ label, value, icon: Icon, color = 'text-blue-300' }: { label: string; value: string; icon: React.ElementType; color?: string }) {
  return (
    <div className="rounded-xl border border-white/10 bg-white/5 p-4">
      <div className="flex items-center gap-2 mb-1">
        <Icon className={cn('h-4 w-4', color)} />
        <p className="text-xs font-medium uppercase text-slate-400">{label}</p>
      </div>
      <p className="text-lg font-semibold text-white">{value}</p>
    </div>
  );
}

export default function SuperAdminUsersPage() {
  const [search, setSearch] = useState('');
  const [selectedUser, setSelectedUser] = useState<UserProfile | null>(null);
  const [showForm, setShowForm] = useState(false);
  const [roles, setRoles] = useState<RoleInfo[]>([]);
  const [confirmAction, setConfirmAction] = useState<{ type: 'ban' | 'freeze' | 'suspend' | 'activate' | 'terminate'; user: UserProfile } | null>(null);
  const [actionLoading, setActionLoading] = useState(false);
  const [actionError, setActionError] = useState<string | null>(null);

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

  useEffect(() => {
      adminService.listRoles().then((r) => setRoles(safeArray<RoleInfo>(r))).catch(() => setRoles([]));
  }, []);

  const handleExportExcel = async () => {
    try {
      const response = await adminService.exportUsersExcel();
      const filename = _extractFilename(response, `users-export-${new Date().toISOString().slice(0,10)}.xlsx`);
      downloadBlob(response.data, filename);
    } catch (err) {
      setActionError(getErrorMessage(err));
    }
  };

  const handleExportPdf = async () => {
    try {
      const response = await adminService.exportUsersPdf();
      const filename = _extractFilename(response, `users-export-${new Date().toISOString().slice(0,10)}.pdf`);
      downloadBlob(response.data, filename);
    } catch (err) {
      setActionError(getErrorMessage(err));
    }
  };

  const handleConfirmAction = async (reason: string, extra?: string) => {
    if (!confirmAction) return;
    setActionLoading(true);
    setActionError(null);
    try {
      if (confirmAction.type === 'ban') {
        await adminService.banUserBySuperAdmin(confirmAction.user.id, reason, extra);
      } else if (confirmAction.type === 'freeze') {
        await adminService.freezeUserWalletBySuperAdmin(confirmAction.user.id, reason, extra);
      } else if (confirmAction.type === 'suspend') {
        await adminService.suspendUser(confirmAction.user.id, reason, extra);
      } else if (confirmAction.type === 'activate') {
        await adminService.activateUser(confirmAction.user.id, reason || undefined);
      } else if (confirmAction.type === 'terminate') {
        await adminService.terminateUser(confirmAction.user.id, reason, extra);
        setSelectedUser(null);
      }
      refetch();
      setConfirmAction(null);
    } catch (err: any) {
      setActionError(getErrorMessage(err));
    } finally {
      setActionLoading(false);
    }
  };

  const handleQuickAction = async (type: 'ban' | 'freeze' | 'suspend' | 'activate' | 'terminate', user: UserProfile) => {
    setConfirmAction({ type, user });
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-white">All Users</h1>
          <p className="text-slate-400">Search and manage all platform users.</p>
        </div>
        <Tooltip content="Create a new user account manually.">
          <button
            onClick={() => 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 User
          </button>
        </Tooltip>
      </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 || 'Failed to load users'}
          <button onClick={() => refetch()} className="ml-4 underline">Retry</button>
        </div>
      )}

      {actionError && (
        <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-400 flex items-center justify-between">
          <span>{actionError}</span>
          <button onClick={() => setActionError(null)} className="ml-4 text-red-300 hover:text-white">&times;</button>
        </div>
      )}

      <div className="flex items-center justify-between gap-4">
        <input
          type="text"
          placeholder="Search users by email, name, or phone..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="w-full max-w-md 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 className="flex items-center gap-2">
          <Tooltip content="Download all users data as an Excel spreadsheet file.">
            <button
              onClick={handleExportExcel}
              disabled={loading}
              className="rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-sm text-slate-300 hover:bg-white/10 disabled:opacity-50 flex items-center gap-2"
            >
              <FileText className="h-4 w-4" /> Export Excel
            </button>
          </Tooltip>
          <Tooltip content="Download all users data as a PDF document.">
            <button
              onClick={handleExportPdf}
              disabled={loading}
              className="rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-sm text-slate-300 hover:bg-white/10 disabled:opacity-50 flex items-center gap-2"
            >
              <FileText className="h-4 w-4" /> Export PDF
            </button>
          </Tooltip>
        </div>
      </div>

      {loading ? (
        <TableSkeleton rows={8} />
      ) : (
        <div className="overflow-x-auto rounded-xl border border-white/10">
          <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">User</th>
                <th className="px-4 py-3">Email</th>
                <th className="px-4 py-3">Role</th>
                <th className="px-4 py-3">Status</th>
                <th className="px-4 py-3">KYC</th>
                <th className="px-4 py-3">Wallet</th>
                <th className="px-4 py-3">Joined</th>
                <th className="px-4 py-3 text-right">Actions</th>
              </tr>
            </thead>
              <tbody className="divide-y divide-white/5">
                {(users || []).map((user) => (
                <tr
                  key={user.id}
                  onClick={() => setSelectedUser(user)}
                  className="hover:bg-white/5 cursor-pointer"
                >
                  <td className="px-4 py-3 text-white">{user.firstName} {user.lastName}</td>
                  <td className="px-4 py-3 text-slate-300">{user.email}</td>
                  <td className="px-4 py-3 text-slate-300">
                    <span className="rounded-full bg-blue-500/20 px-2 py-1 text-xs text-blue-300">
                      {user.role?.name || 'USER'}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    {user.isBanned ? (
                      <span className="rounded-full bg-red-500/20 px-2 py-1 text-xs text-red-300">Banned</span>
                    ) : user.isDisabled ? (
                      <span className="rounded-full bg-yellow-500/20 px-2 py-1 text-xs text-yellow-300">Disabled</span>
                    ) : (
                      <span className="rounded-full bg-green-500/20 px-2 py-1 text-xs text-green-300">Active</span>
                    )}
                  </td>
                  <td className="px-4 py-3 text-slate-300">
                    {user.isKycVerified ? 'Verified' : 'Pending'}
                  </td>
                  <td className="px-4 py-3 text-slate-300">
                    {user.wallet ? `${Number(user.wallet.balance).toFixed(2)}` : 'N/A'}
                  </td>
                   <td className="px-4 py-3 text-slate-300">
                     {new Date(user.createdAt).toLocaleDateString()}
                   </td>
                    <td className="px-4 py-3 text-right">
                      <div className="flex items-center justify-end gap-1">
                        <Tooltip content="Stop this user from accessing their account. They cannot log in until you unban them.">
                          <button
                            onClick={(e) => { e.stopPropagation(); handleQuickAction('ban', user); }}
                            className="rounded p-1.5 text-red-400 hover:bg-red-500/20"
                          >
                            <Ban className="h-4 w-4" />
                          </button>
                        </Tooltip>
                        <Tooltip content="Block all money transactions for this user. They cannot send or receive money.">
                          <button
                            onClick={(e) => { e.stopPropagation(); handleQuickAction('freeze', user); }}
                            className="rounded p-1.5 text-amber-400 hover:bg-amber-500/20"
                          >
                            <Lock className="h-4 w-4" />
                          </button>
                        </Tooltip>
                        <Tooltip content="Temporarily stop this user from using the platform. They can be activated later.">
                          <button
                            onClick={(e) => { e.stopPropagation(); handleQuickAction('suspend', user); }}
                            className="rounded p-1.5 text-orange-400 hover:bg-orange-500/20"
                          >
                            <UserX className="h-4 w-4" />
                          </button>
                        </Tooltip>
                        <Tooltip content="Allow this user to use the platform again after being banned or suspended.">
                          <button
                            onClick={(e) => { e.stopPropagation(); handleQuickAction('activate', user); }}
                            className="rounded p-1.5 text-green-400 hover:bg-green-500/20"
                          >
                            <CheckSquare className="h-4 w-4" />
                          </button>
                        </Tooltip>
                        <Tooltip content="PERMANENTLY DELETE this user and ALL their data. This cannot be undone. Use with extreme caution.">
                          <button
                            onClick={(e) => { e.stopPropagation(); handleQuickAction('terminate', user); }}
                            className="rounded p-1.5 text-red-500 hover:bg-red-600/20"
                          >
                            <Trash2 className="h-4 w-4" />
                          </button>
                        </Tooltip>
                      </div>
                    </td>
                   </tr>
               ))}
               {(users || []).length === 0 && (
                 <tr>
                   <td colSpan={8} className="px-4 py-8 text-center text-slate-400">
                     No users found.
                   </td>
                 </tr>
               )}
             </tbody>
          </table>
        </div>
      )}

      {selectedUser && (
        <UserDetailModal user={selectedUser} onClose={() => setSelectedUser(null)} onRefresh={refetch} />
      )}

      {showForm && (
        <UserFormDialog roles={roles} onClose={() => setShowForm(false)} onSuccess={refetch} />
      )}

      {confirmAction && (
        <ConfirmDialog
          title={`Confirm ${confirmAction.type.charAt(0).toUpperCase() + confirmAction.type.slice(1)}`}
          description={
            confirmAction.type === 'terminate'
              ? `This will PERMANENTLY DELETE user ${confirmAction.user.email} and ALL associated data. This action CANNOT be undone.`
              : confirmAction.type === 'ban'
                ? `This will ban user ${confirmAction.user.email}. They will not be able to log in.`
                : confirmAction.type === 'freeze'
                  ? `This will freeze the wallet of ${confirmAction.user.email}. All transactions will be blocked.`
                  : confirmAction.type === 'suspend'
                    ? `This will suspend user ${confirmAction.user.email}.`
                    : `This will activate user ${confirmAction.user.email}.`
          }
          confirmLabel={confirmAction.type === 'terminate' ? 'Yes, Delete Permanently' : confirmAction.type === 'ban' ? 'Yes, Ban User' : confirmAction.type === 'freeze' ? 'Yes, Freeze Wallet' : confirmAction.type === 'suspend' ? 'Yes, Suspend' : 'Yes, Activate'}
          confirmVariant={confirmAction.type === 'terminate' || confirmAction.type === 'ban' ? 'danger' : confirmAction.type === 'freeze' ? 'warning' : 'primary'}
          onConfirm={handleConfirmAction}
          onClose={() => setConfirmAction(null)}
          loading={actionLoading}
          confirmTooltip={
            confirmAction.type === 'ban' ? 'Stop this user from accessing their account. They cannot log in until you unban them.' :
            confirmAction.type === 'freeze' ? 'Block all money transactions for this user. They cannot send or receive money.' :
            confirmAction.type === 'suspend' ? 'Temporarily stop this user from using the platform. They can be activated later.' :
            confirmAction.type === 'activate' ? 'Allow this user to use the platform again after being banned or suspended.' :
            confirmAction.type === 'terminate' ? 'PERMANENTLY DELETE this user and ALL their data. This cannot be undone. Use with extreme caution.' :
            undefined
          }
        />
      )}
    </div>
  );
}
