'use client';

import { useEffect, useState } from 'react';
import { api } from '@/lib/api';
import { ShieldCheck, ShieldAlert, Lock, Unlock, Users2, Crown, Store, Ban, WalletCards, Eye, Search, SlidersHorizontal } from 'lucide-react';
import { useAuthStore } from '@/store/authStore';
import { DataTable, ColumnDef } from '@/components/ui/DataTable';

export default function AdminUsersPage() {
  const [users, setUsers] = useState<any[]>([]);
  const [totalUsers, setTotalUsers] = useState(0);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [roleFilter, setRoleFilter] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const [selectedUser, setSelectedUser] = useState<any | null>(null);
  const [selectedUserDetail, setSelectedUserDetail] = useState<any | null>(null);
  const [selectedUserDetailLoading, setSelectedUserDetailLoading] = useState(false);
  const [editingUser, setEditingUser] = useState<any | null>(null);
  const [savingUser, setSavingUser] = useState(false);
  const [detailTab, setDetailTab] = useState<'profile' | 'security' | 'deposits' | 'activity'>('profile');
  const [newPassword, setNewPassword] = useState('');
  const [balanceAmount, setBalanceAmount] = useState('');
  const [balanceOperation, setBalanceOperation] = useState<'CREDIT' | 'DEBIT'>('CREDIT');
  const [balanceNote, setBalanceNote] = useState('');
  const [balanceSubmitting, setBalanceSubmitting] = useState(false);
  const token = useAuthStore((s) => s.token);

  const fetchUsers = async () => {
    if (!token) return;
    setLoading(true);
    try {
      const res = await api.get('/admin/users', {
        params: { search, role: roleFilter || undefined, limit: 100 }
      });
      const data = res.data?.data || res.data || [];
      setTotalUsers(Number(res.data?.total ?? data.length));
      setUsers(data.filter((u: any) => !statusFilter || u.status === statusFilter));
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    const delayDebounceFn = setTimeout(() => {
      fetchUsers();
    }, search ? 250 : 0);
    return () => clearTimeout(delayDebounceFn);
  }, [search, roleFilter, statusFilter, token]);

  const fetchUserDetail = async (id: string) => {
    setSelectedUserDetailLoading(true);
    try {
      const res = await api.get(`/admin/users/${id}/detail`);
      setSelectedUserDetail(res.data);
    } catch (error) {
      console.error(error);
      setSelectedUserDetail(null);
    } finally {
      setSelectedUserDetailLoading(false);
    }
  };

  const handleOpenUser = (user: any) => {
    setSelectedUser(user);
    setSelectedUserDetail(null);
    setDetailTab('profile');
    setEditingUser({
      id: user.id,
      email: user.email,
      name: user.name || '',
      phone: user.phone || '',
      address: user.address || '',
      city: user.city || '',
      district: user.district || '',
      ward: user.ward || '',
      facebookUrl: user.facebookUrl || '',
      discordUrl: user.discordUrl || '',
      youtubeUrl: user.youtubeUrl || '',
      telegramUrl: user.telegramUrl || '',
      status: user.status,
      role: user.role?.name || 'BUYER',
      balance: user.balance || 0,
    });
    fetchUserDetail(user.id);
  };

  const handleCloseUserModal = () => {
    setSelectedUser(null);
    setSelectedUserDetail(null);
    setSelectedUserDetailLoading(false);
    setEditingUser(null);
    setNewPassword('');
    setBalanceAmount('');
    setBalanceOperation('CREDIT');
    setBalanceNote('');
  };

  const handleBalanceAdjustment = async () => {
    if (!selectedUser || !balanceAmount.trim() || Number(balanceAmount) <= 0) {
      alert('Vui lòng nhập số tiền hợp lệ.');
      return;
    }

    try {
      setBalanceSubmitting(true);
      await api.post('/admin/payments/adjust', {
        userIdentifier: selectedUser.id,
        amount: Number(balanceAmount),
        currency: 'VND',
        operation: balanceOperation,
        note: balanceNote.trim() || `Admin ${balanceOperation === 'CREDIT' ? 'credit' : 'debit'} adjustment`,
      });
      alert(balanceOperation === 'CREDIT' ? 'Đã cộng tiền thành công.' : 'Đã trừ tiền thành công.');
      setBalanceAmount('');
      setBalanceNote('');
      await fetchUserDetail(selectedUser.id);
      await fetchUsers();
    } catch (error: any) {
      alert(error?.response?.data?.message || 'Không thể điều chỉnh số dư.');
    } finally {
      setBalanceSubmitting(false);
    }
  };

  const handleResetPassword = async () => {
    if (!selectedUser || newPassword.length < 8) { alert('Mật khẩu mới phải có ít nhất 8 ký tự.'); return; }
    try { await api.patch(`/admin/users/${selectedUser.id}/password`, { newPassword }); setNewPassword(''); alert('Đã đặt lại mật khẩu thành công.'); }
    catch (error: any) { alert(error?.response?.data?.message || 'Không thể đặt lại mật khẩu.'); }
  };

  const handleFieldChange = (key: string, value: string) => {
    if (!editingUser) return;
    setEditingUser((prev: any) => ({ ...prev, [key]: value }));
  };

  const handleSaveUser = async () => {
    if (!token || !editingUser) return;
    setSavingUser(true);
    try {
      const { id, email, status, balance, ...updates } = editingUser;
      const res = await api.patch(`/admin/users/${id}`, updates);
      const updatedUser = res.data;
      setUsers((prev) => prev.map((u) => (u.id === updatedUser.id ? updatedUser : u)));
      setSelectedUser(updatedUser);
      setEditingUser((prev: any) => ({
        ...updatedUser,
        role: updatedUser.role?.name || updatedUser.role || prev?.role || 'BUYER',
      }));
      if (selectedUser?.id === updatedUser.id) {
        await fetchUserDetail(updatedUser.id);
      }
      alert('Cập nhật thông tin người dùng thành công');
    } catch (error) {
      console.error(error);
      alert('Cập nhật thông tin người dùng thất bại');
    } finally {
      setSavingUser(false);
    }
  };

  const handleToggleStatus = async (id: string, currentStatus: string) => {
    if (!token) return;
    const newStatus = currentStatus === 'ACTIVE' ? 'BANNED' : 'ACTIVE';
    const msg = newStatus === 'BANNED' ? 'Bạn có chắc muốn KHÓA tài khoản này?' : 'Bạn có chắc muốn MỞ KHÓA tài khoản này?';

    if (!confirm(msg)) return;

    try {
      await api.patch(`/admin/users/${id}/status`, { status: newStatus });
      if (selectedUser?.id === id) {
        setSelectedUser((current: any) => ({ ...current, status: newStatus }));
        setEditingUser((current: any) => current ? ({ ...current, status: newStatus }) : current);
      }
      fetchUsers();
    } catch {
      alert('Cập nhật trạng thái thất bại');
    }
  };

  const handleInstantWithdrawal = async () => {
    if (!selectedUser) return;
    const enabled = !Boolean(selectedUserDetail?.withdrawalSettings?.instantWithdrawal);
    const message = enabled
      ? 'Bật rút tiền ngay cho Seller này? Chỉ dùng để kiểm thử, tiền bán đang chờ sẽ được mở khi Seller tải lại trang rút tiền.'
      : 'Tắt rút tiền ngay và áp dụng lại thời gian chờ 7 ngày cho các đơn mới?';
    if (!confirm(message)) return;
    try {
      await api.patch(`/admin/users/${selectedUser.id}/withdrawal-access`, { instantWithdrawal: enabled });
      await fetchUserDetail(selectedUser.id);
      alert(enabled ? 'Đã bật quyền rút tiền ngay để kiểm thử.' : 'Đã tắt quyền rút tiền ngay.');
    } catch (error: any) {
      alert(error?.response?.data?.message || 'Không thể cập nhật quyền rút tiền.');
    }
  };

  const summary = {
    // The API is paginated (20 records per request); always use its total so
    // importing more users does not make the dashboard show only page one.
    total: totalUsers,
    walletBalance: users.reduce((sum, user) => sum + Number(user.balance || 0), 0),
    admins: users.filter((u) => u.role?.name === 'ADMIN' || u.role?.name === 'SUPER_ADMIN').length,
    sellers: users.filter((u) => u.role?.name === 'SELLER').length,
    buyers: users.filter((u) => u.role?.name === 'BUYER' || !u.role?.name).length,
    banned: users.filter((u) => u.status === 'BANNED').length,
  };

  const formatMoney = (value: unknown) => `${Number(value || 0).toLocaleString('vi-VN')}đ`;
  const formatDate = (value?: string | Date | null) => value
    ? new Date(value).toLocaleString('vi-VN', { dateStyle: 'short', timeStyle: 'short' })
    : '—';
  const isOnline = (value?: string | Date | null) => Boolean(value) && Date.now() - new Date(value as string).getTime() < 5 * 60 * 1000;

  const columns: ColumnDef<any>[] = [
    {
      header: 'Thành viên',
      cell: (u) => (
        <div className="flex items-center gap-3">
          <div className="w-9 h-9 rounded-lg bg-primary/10 flex items-center justify-center text-primary font-bold">
            {u.name?.charAt(0).toUpperCase() || 'U'}
          </div>
          <div>
            <p className="text-foreground text-sm font-bold leading-tight">{u.name || 'Chưa cập nhật'}</p>
            <p className="text-muted-foreground text-[11px] truncate max-w-[180px]">{u.email}</p>
            <p className="mt-0.5 font-mono text-[10px] font-bold tracking-wide text-cyan-400">ID: {u.memberCode || '—'}</p>
          </div>
        </div>
      ),
      align: 'left'
    },
    {
      header: 'Vai trò',
      cell: (u) => (
        <span className={`text-[10px] font-bold px-2.5 py-1 rounded-full border ${
          u.role?.name === 'SUPER_ADMIN' || u.role?.name === 'ADMIN' ? 'bg-danger/10 text-danger border-danger/20' :
          u.role?.name === 'SELLER' ? 'bg-blue-500/10 text-blue-400 border-blue-500/20' :
          'bg-muted text-muted-foreground border-border'
        }`}>
          {u.role?.name || 'BUYER'}
        </span>
      ),
      align: 'center'
    },
    {
      header: 'Số dư',
      cell: (u) => <span className="font-bold text-primary whitespace-nowrap">{formatMoney(u.balance)}</span>,
      align: 'right'
    },
    {
      header: 'Tổng nạp',
      cell: (u) => <span className="font-semibold text-emerald-400 whitespace-nowrap">{formatMoney(u.totalDeposited)}</span>,
      align: 'right'
    },
    {
      header: 'Trạng thái',
      cell: (u) => (
        <span className={`flex items-center justify-center gap-1 text-[10px] font-bold px-2.5 py-1 rounded-full w-fit mx-auto ${
          u.status === 'ACTIVE' ? 'text-success bg-success/10' : 'text-warning bg-warning/10'
        }`}>
          {u.status === 'ACTIVE' ? <ShieldCheck className="w-3 h-3" /> : <ShieldAlert className="w-3 h-3" />}
          {u.status}
        </span>
      ),
      align: 'center'
    },
    {
      header: 'Hoạt động',
      cell: (u) => (
        <div className="text-center">
          <span className={`inline-flex items-center gap-1 text-[10px] font-bold ${isOnline(u.lastActiveAt) ? 'text-emerald-400' : 'text-muted-foreground'}`}>
            <span className={`h-1.5 w-1.5 rounded-full ${isOnline(u.lastActiveAt) ? 'bg-emerald-400 animate-pulse' : 'bg-muted-foreground'}`} />
            {isOnline(u.lastActiveAt) ? 'Trực tuyến' : 'Ngoại tuyến'}
          </span>
          <p className="mt-1 text-[10px] text-muted-foreground whitespace-nowrap">{formatDate(u.lastActiveAt)}</p>
        </div>
      ),
      align: 'center'
    },
    {
      header: 'Hành động',
      cell: (u) => (
        <div className="flex items-center justify-end gap-2">
          <button
            onClick={() => handleOpenUser(u)}
            className="inline-flex items-center gap-1 px-2.5 py-1.5 rounded-lg bg-primary/10 text-xs text-primary hover:bg-primary/20 transition-colors"
            title="Xem và chỉnh sửa"
          >
            <Eye className="h-3.5 w-3.5" /> Xem
          </button>
          <button
            onClick={() => handleToggleStatus(u.id, u.status)}
            className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-muted text-muted-foreground transition-colors"
            title={u.status === 'ACTIVE' ? 'Khóa tài khoản' : 'Mở khóa tài khoản'}
          >
            {u.status === 'ACTIVE' ? <Lock className="w-4 h-4 text-warning" /> : <Unlock className="w-4 h-4 text-success" />}
          </button>
        </div>
      ),
      align: 'right'
    }
  ];

  const filters = (
    <div className="flex flex-col lg:flex-row gap-2">
      <select
        value={roleFilter}
        onChange={(e) => setRoleFilter(e.target.value)}
        className="bg-background border border-border rounded-lg px-3 py-2 text-foreground text-xs focus:outline-none focus:border-primary/50 min-w-[170px]"
      >
        <option value="">Tất cả vai trò</option>
        <option value="BUYER">Khách hàng (BUYER)</option>
        <option value="SELLER">Người bán (SELLER)</option>
        <option value="ADMIN">Quản trị viên (ADMIN)</option>
      </select>
      <select
        value={statusFilter}
        onChange={(e) => setStatusFilter(e.target.value)}
        className="bg-background border border-border rounded-lg px-3 py-2 text-foreground text-xs focus:outline-none focus:border-primary/50 min-w-[150px]"
      >
        <option value="">Tất cả trạng thái</option>
        <option value="ACTIVE">ACTIVE</option>
        <option value="BANNED">BANNED</option>
      </select>
    </div>
  );

  return (
    <div className="space-y-5">
      <div className="flex flex-col gap-1 border-b border-border pb-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="flex items-center gap-2 text-xl font-black text-foreground"><Users2 className="h-5 w-5 text-primary" /> Users</h1>
          <p className="mt-1 text-sm text-muted-foreground">Theo dõi tài khoản, số dư, lịch sử nạp tiền và quyền truy cập.</p>
        </div>
        <span className="text-xs text-muted-foreground">Dữ liệu hiển thị theo bộ lọc hiện tại</span>
      </div>

      <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
        {[
          { label: 'Tổng thành viên', value: summary.total, icon: Users2, tone: 'text-emerald-400 bg-emerald-400/10' },
          { label: 'Số dư đang hiển thị', value: formatMoney(summary.walletBalance), icon: WalletCards, tone: 'text-cyan-400 bg-cyan-400/10' },
          { label: 'Quản trị viên', value: summary.admins, icon: Crown, tone: 'text-amber-400 bg-amber-400/10' },
          { label: 'Tài khoản bị khóa', value: summary.banned, icon: Ban, tone: 'text-rose-400 bg-rose-400/10' },
        ].map((item) => {
          const Icon = item.icon;
          return (
            <div key={item.label} className="rounded-xl border border-border bg-card px-4 py-3 shadow-sm">
              <div className="flex items-center gap-3">
                <div className={`flex h-9 w-9 items-center justify-center rounded-lg ${item.tone}`}><Icon className="h-4 w-4" /></div>
                <div>
                  <p className="text-lg font-black leading-none text-foreground">{item.value}</p>
                  <p className="mt-1 text-[10px] font-bold uppercase tracking-wide text-muted-foreground">{item.label}</p>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      <section className="rounded-2xl border border-border bg-card/70 p-3 sm:p-4">
        <div className="mb-3 flex flex-col gap-3 border-b border-border pb-3 lg:flex-row lg:items-center lg:justify-between">
          <div>
            <h2 className="flex items-center gap-2 text-sm font-black uppercase tracking-wide text-foreground"><SlidersHorizontal className="h-4 w-4 text-primary" /> Danh sách thành viên</h2>
            <p className="mt-1 text-xs text-muted-foreground">Mở hồ sơ để kiểm tra lịch sử nạp tiền, đơn hàng và thay đổi trạng thái.</p>
          </div>
          <div className="flex items-center gap-2 text-xs text-muted-foreground"><Search className="h-4 w-4" /> Tìm và lọc ngay trên danh sách</div>
        </div>
        <DataTable
          title=""
          columns={columns}
          data={users}
          searchPlaceholder="Tìm theo mã thành viên, tên hoặc email..."
          searchValue={search}
          onSearchChange={setSearch}
          filters={filters}
          emptyMessage={loading ? 'Đang tải dữ liệu...' : 'Không tìm thấy người dùng nào'}
        />
      </section>

      {selectedUser && editingUser && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 p-2 sm:p-5">
          <div className="max-h-[96vh] w-full max-w-[1500px] overflow-y-auto rounded-xl border border-border bg-[#0c0d0f] p-4 shadow-2xl sm:p-5">
            <div className="flex flex-col gap-4 border-b border-border pb-4 sm:flex-row sm:items-start sm:justify-between">
              <div>
                <p className="text-xs font-bold uppercase tracking-wide text-muted-foreground">Chỉnh sửa thành viên</p>
                <h2 className="mt-1 text-xl font-black text-foreground">{selectedUser.name || selectedUser.email}</h2>
                <div className="mt-2 flex flex-wrap items-center gap-2 text-xs"><span className={`rounded px-2 py-1 font-bold ${selectedUser.status === 'ACTIVE' ? 'bg-emerald-500/10 text-emerald-400' : 'bg-rose-500/10 text-rose-400'}`}>{selectedUser.status}</span><span className="rounded bg-cyan-500/10 px-2 py-1 font-mono font-bold tracking-wide text-cyan-300">ID: {selectedUser.memberCode || '—'}</span><span className="text-muted-foreground">{selectedUser.email}</span></div>
              </div>
              <div className="flex items-center gap-2"><button type="button" onClick={() => handleToggleStatus(selectedUser.id, selectedUser.status)} className="rounded-lg border border-amber-500/30 px-3 py-2 text-xs font-bold text-amber-300 hover:bg-amber-500/10">{selectedUser.status === 'ACTIVE' ? 'Khóa tài khoản' : 'Mở khóa'}</button><button type="button" onClick={handleCloseUserModal} className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-xs font-bold text-muted-foreground hover:bg-white/10">Đóng</button></div>
            </div>

            <div className="mt-4 grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
              {[
                { label: 'Ví chính', value: formatMoney(selectedUser.balance), tone: 'text-emerald-400' },
                { label: 'Tổng tiền nạp', value: formatMoney(selectedUser.totalDeposited), tone: 'text-cyan-400' },
                { label: 'Đã sử dụng', value: String((selectedUserDetail?.stats?.buyerOrders || 0) + (selectedUserDetail?.stats?.sellerOrders || 0)) + ' đơn', tone: 'text-amber-400' },
                { label: 'Số tiền rút', value: String(selectedUserDetail?.stats?.withdrawals || 0) + ' yêu cầu', tone: 'text-rose-400' },
              ].map((item) => <div key={item.label} className="rounded-lg border border-white/5 bg-black px-4 py-3"><p className="text-[10px] font-bold uppercase tracking-wide text-muted-foreground">{item.label}</p><p className={`mt-1 text-lg font-black ${item.tone}`}>{selectedUserDetailLoading ? '...' : item.value}</p></div>)}
            </div>

            <div className="mt-5 flex flex-wrap gap-2 border-b border-border pb-3">
              {[['profile', 'Thông tin cơ bản'], ['security', 'Bảo mật'], ['deposits', 'Nạp tiền & ví'], ['activity', 'Hoạt động hệ thống']].map(([key, label]) => <button key={key} type="button" onClick={() => setDetailTab(key as typeof detailTab)} className={`rounded-lg px-3 py-2 text-xs font-bold transition ${detailTab === key ? 'bg-emerald-500/15 text-emerald-300 ring-1 ring-emerald-500/30' : 'text-muted-foreground hover:bg-white/5 hover:text-foreground'}`}>{label}</button>)}
            </div>

            <div className={`${detailTab === 'security' ? '' : 'hidden'} mt-6 grid gap-4 md:grid-cols-2`}>
              <div className="rounded-xl border border-border bg-background p-4"><p className="text-xs font-bold uppercase text-muted-foreground">Email đăng nhập</p><p className="mt-2 break-all text-sm font-semibold text-foreground">{selectedUser.email}</p><p className="mt-2 text-xs text-muted-foreground">Trạng thái email: {selectedUser.emailVerified ? 'Đã xác minh' : 'Chưa xác minh'}</p></div>
              <div className="rounded-xl border border-border bg-background p-4"><p className="text-xs font-bold uppercase text-muted-foreground">Đặt lại mật khẩu</p><p className="mt-2 text-xs text-muted-foreground">Mật khẩu hiện tại được mã hóa, không thể xem.</p><input type="password" value={newPassword} onChange={(event) => setNewPassword(event.target.value)} placeholder="Mật khẩu mới, ít nhất 8 ký tự" className="mt-3 w-full rounded-lg border border-border bg-card px-3 py-2 text-sm text-foreground" /><button type="button" onClick={handleResetPassword} className="mt-3 rounded-lg bg-red-500 px-3 py-2 text-xs font-bold text-white hover:bg-red-400">Lưu mật khẩu mới</button></div>
            </div>

            <div className={`${detailTab === 'profile' ? '' : 'hidden'} grid gap-4 mt-6 md:grid-cols-2`}>
              <div>
                <label className="text-xs font-semibold uppercase text-muted-foreground">Họ tên</label>
                <input
                  type="text"
                  value={editingUser.name}
                  onChange={(e) => handleFieldChange('name', e.target.value)}
                  className="w-full bg-background border border-border rounded-xl px-4 py-3 text-sm text-foreground focus:outline-none focus:border-primary/50"
                />
              </div>
              <div>
                <label className="text-xs font-semibold uppercase text-muted-foreground">Vai trò</label>
                <select
                  value={editingUser.role}
                  onChange={(e) => handleFieldChange('role', e.target.value)}
                  className="w-full bg-background border border-border rounded-xl px-4 py-3 text-sm text-foreground focus:outline-none focus:border-primary/50"
                >
                  <option value="BUYER">Khách hàng (BUYER)</option>
                  <option value="SELLER">Người bán (SELLER)</option>
                  <option value="ADMIN">Quản trị viên (ADMIN)</option>
                  <option value="SUPER_ADMIN">Siêu quản trị (SUPER_ADMIN)</option>
                </select>
              </div>
              <div>
                <label className="text-xs font-semibold uppercase text-muted-foreground">Số điện thoại</label>
                <input
                  type="text"
                  value={editingUser.phone}
                  onChange={(e) => handleFieldChange('phone', e.target.value)}
                  className="w-full bg-background border border-border rounded-xl px-4 py-3 text-sm text-foreground focus:outline-none focus:border-primary/50"
                />
              </div>
              <div className="md:col-span-2">
                <label className="text-xs font-semibold uppercase text-muted-foreground">Địa chỉ</label>
                <input
                  type="text"
                  value={editingUser.address}
                  onChange={(e) => handleFieldChange('address', e.target.value)}
                  className="w-full bg-background border border-border rounded-xl px-4 py-3 text-sm text-foreground focus:outline-none focus:border-primary/50"
                />
              </div>
              <div>
                <label className="text-xs font-semibold uppercase text-muted-foreground">Thành phố</label>
                <input
                  type="text"
                  value={editingUser.city}
                  onChange={(e) => handleFieldChange('city', e.target.value)}
                  className="w-full bg-background border border-border rounded-xl px-4 py-3 text-sm text-foreground focus:outline-none focus:border-primary/50"
                />
              </div>
              <div>
                <label className="text-xs font-semibold uppercase text-muted-foreground">Quận / Huyện</label>
                <input
                  type="text"
                  value={editingUser.district}
                  onChange={(e) => handleFieldChange('district', e.target.value)}
                  className="w-full bg-background border border-border rounded-xl px-4 py-3 text-sm text-foreground focus:outline-none focus:border-primary/50"
                />
              </div>
              <div>
                <label className="text-xs font-semibold uppercase text-muted-foreground">Phường / Xã</label>
                <input
                  type="text"
                  value={editingUser.ward}
                  onChange={(e) => handleFieldChange('ward', e.target.value)}
                  className="w-full bg-background border border-border rounded-xl px-4 py-3 text-sm text-foreground focus:outline-none focus:border-primary/50"
                />
              </div>
            </div>

            <div className={`${detailTab === 'profile' ? '' : 'hidden'} grid gap-4 mt-6 md:grid-cols-2`}>
              <div>
                <label className="text-xs font-semibold uppercase text-muted-foreground">Facebook URL</label>
                <input
                  type="text"
                  value={editingUser.facebookUrl}
                  onChange={(e) => handleFieldChange('facebookUrl', e.target.value)}
                  placeholder="https://facebook.com/..."
                  className="w-full bg-background border border-border rounded-xl px-4 py-3 text-sm text-foreground focus:outline-none focus:border-primary/50"
                />
              </div>
              <div>
                <label className="text-xs font-semibold uppercase text-muted-foreground">Discord URL</label>
                <input
                  type="text"
                  value={editingUser.discordUrl}
                  onChange={(e) => handleFieldChange('discordUrl', e.target.value)}
                  placeholder="https://discord.gg/..."
                  className="w-full bg-background border border-border rounded-xl px-4 py-3 text-sm text-foreground focus:outline-none focus:border-primary/50"
                />
              </div>
              <div>
                <label className="text-xs font-semibold uppercase text-muted-foreground">YouTube URL</label>
                <input
                  type="text"
                  value={editingUser.youtubeUrl}
                  onChange={(e) => handleFieldChange('youtubeUrl', e.target.value)}
                  placeholder="https://youtube.com/..."
                  className="w-full bg-background border border-border rounded-xl px-4 py-3 text-sm text-foreground focus:outline-none focus:border-primary/50"
                />
              </div>
              <div>
                <label className="text-xs font-semibold uppercase text-muted-foreground">Telegram URL</label>
                <input
                  type="text"
                  value={editingUser.telegramUrl}
                  onChange={(e) => handleFieldChange('telegramUrl', e.target.value)}
                  placeholder="https://t.me/..."
                  className="w-full bg-background border border-border rounded-xl px-4 py-3 text-sm text-foreground focus:outline-none focus:border-primary/50"
                />
              </div>
            </div>

            <div className={`${detailTab === 'profile' ? '' : 'hidden'} mt-8 grid gap-4 md:grid-cols-2`}>
              <div className="rounded-3xl border border-border bg-background p-4">
                <p className="text-sm font-semibold text-foreground mb-3">Ví Buyer</p>
                <div className="space-y-2 text-sm text-foreground">
                  <p>Có thể dùng: {selectedUserDetail?.accountWallet ? Number(selectedUserDetail.accountWallet.availableBalance).toLocaleString('vi-VN') + 'đ' : '-'}</p>
                  <p>Đang khóa: {selectedUserDetail?.accountWallet ? Number(selectedUserDetail.accountWallet.lockedBalance).toLocaleString('vi-VN') + 'đ' : '-'}</p>
                  <p>Trạng thái: {selectedUserDetail?.accountWallet?.status || '-'}</p>
                </div>
              </div>
              <div className="rounded-3xl border border-border bg-background p-4">
                <p className="text-sm font-semibold text-foreground mb-3">Ví Seller</p>
                <div className="space-y-2 text-sm text-foreground">
                  <p>Có thể dùng: {selectedUserDetail?.sellerWallet ? Number(selectedUserDetail.sellerWallet.availableBalance).toLocaleString('vi-VN') + 'đ' : '-'}</p>
                  <p>Đang chờ: {selectedUserDetail?.sellerWallet ? Number(selectedUserDetail.sellerWallet.pendingBalance).toLocaleString('vi-VN') + 'đ' : '-'}</p>
                  <p>Trạng thái: {selectedUserDetail?.sellerWallet?.status || '-'}</p>
                </div>
                {(selectedUser.role?.name === 'SELLER' || selectedUserDetail?.sellerWallet) && (
                  <div className="mt-4 border-t border-border pt-3">
                    <p className="text-xs font-bold text-foreground">Kiểm thử rút tiền</p>
                    <p className="mt-1 text-[11px] leading-relaxed text-muted-foreground">Bỏ qua mốc chờ 7 ngày cho Seller này. Không bật cho tài khoản vận hành thật.</p>
                    <button type="button" onClick={handleInstantWithdrawal} className={`mt-3 rounded-lg px-3 py-2 text-xs font-bold transition-colors ${selectedUserDetail?.withdrawalSettings?.instantWithdrawal ? 'bg-amber-500/15 text-amber-300 hover:bg-amber-500/25' : 'bg-cyan-500/15 text-cyan-300 hover:bg-cyan-500/25'}`}>
                      {selectedUserDetail?.withdrawalSettings?.instantWithdrawal ? 'Tắt rút tiền ngay' : 'Cho phép rút ngay (test)'}
                    </button>
                  </div>
                )}
              </div>
            </div>

            <div className={`${detailTab === 'profile' ? '' : 'hidden'} mt-6 rounded-xl border border-amber-500/20 bg-amber-500/5 p-4`}>
              <div className="flex flex-col gap-1 sm:flex-row sm:items-center sm:justify-between">
                <div>
                  <p className="text-sm font-bold text-foreground">Điều chỉnh số dư</p>
                  <p className="mt-1 text-xs text-muted-foreground">Thao tác được ghi nhận qua PaymentSession, WalletLedger và AuditLog.</p>
                </div>
                <p className="text-sm font-bold text-amber-300">Hiện tại: {formatMoney(selectedUserDetail?.accountWallet?.availableBalance ?? selectedUser.balance)}</p>
              </div>
              <div className="mt-4 grid gap-3 md:grid-cols-[1fr_180px_1fr_auto] md:items-end">
                <label className="text-xs font-semibold text-muted-foreground">Số tiền
                  <input type="number" min="1" value={balanceAmount} onChange={(event) => setBalanceAmount(event.target.value)} placeholder="Nhập số tiền" className="mt-2 w-full rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground" />
                </label>
                <label className="text-xs font-semibold text-muted-foreground">Thao tác
                  <select value={balanceOperation} onChange={(event) => setBalanceOperation(event.target.value as 'CREDIT' | 'DEBIT')} className="mt-2 w-full rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground">
                    <option value="CREDIT">Cộng tiền</option>
                    <option value="DEBIT">Trừ tiền</option>
                  </select>
                </label>
                <label className="text-xs font-semibold text-muted-foreground">Lý do
                  <input value={balanceNote} onChange={(event) => setBalanceNote(event.target.value)} placeholder="Ghi chú bắt buộc khi cần đối soát" className="mt-2 w-full rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground" />
                </label>
                <button type="button" onClick={handleBalanceAdjustment} disabled={balanceSubmitting || !balanceAmount || Number(balanceAmount) <= 0} className={`rounded-lg px-4 py-2 text-sm font-bold text-white disabled:opacity-50 ${balanceOperation === 'CREDIT' ? 'bg-emerald-600 hover:bg-emerald-500' : 'bg-rose-600 hover:bg-rose-500'}`}>
                  {balanceSubmitting ? 'Đang xử lý...' : balanceOperation === 'CREDIT' ? 'Cộng tiền' : 'Trừ tiền'}
                </button>
              </div>
            </div>

            <div className={`${detailTab === 'deposits' ? '' : 'hidden'} mt-6 overflow-hidden rounded-xl border border-white/10 bg-[#111214]`}>
              <div className="flex items-center justify-between border-b border-white/10 px-5 py-4">
                <div><p className="font-bold text-white">Lịch sử nạp tiền</p><p className="mt-1 text-xs text-gray-500">Đối soát nạp online, yêu cầu nạp và nạp thủ công của tài khoản.</p></div>
                <span className="rounded-full bg-emerald-500/10 px-2.5 py-1 text-xs font-bold text-emerald-300">{selectedUserDetail?.recentDeposits?.length || 0} giao dịch</span>
              </div>
              <div className="max-h-72 overflow-auto">
                {selectedUserDetailLoading ? <p className="p-5 text-sm text-gray-500">Đang tải lịch sử nạp tiền…</p> : selectedUserDetail?.recentDeposits?.length ? <table className="w-full text-left text-sm"><thead className="sticky top-0 bg-[#17181b] text-[11px] uppercase tracking-wide text-gray-500"><tr><th className="px-5 py-3">Thời gian</th><th className="px-3 py-3">Kênh nạp</th><th className="px-3 py-3">Mã tham chiếu</th><th className="px-3 py-3 text-right">Số tiền</th><th className="px-5 py-3 text-right">Trạng thái</th></tr></thead><tbody>{selectedUserDetail.recentDeposits.map((deposit: any) => <tr key={deposit.id} className="border-t border-white/5"><td className="px-5 py-3 text-xs text-gray-400">{new Date(deposit.createdAt).toLocaleString('vi-VN')}</td><td className="px-3 py-3"><p className="font-semibold text-white">{deposit.provider}</p><p className="text-[11px] text-gray-500">{deposit.source === 'MANUAL' ? `Admin: ${deposit.admin || '—'}` : deposit.method || '—'}</p></td><td className="max-w-32 truncate px-3 py-3 text-xs text-gray-400">{deposit.reference || '—'}</td><td className="px-3 py-3 text-right font-bold text-emerald-300">{Number(deposit.amount || 0).toLocaleString('vi-VN')} {deposit.currency || 'VND'}</td><td className="px-5 py-3 text-right"><span className={`rounded-full px-2 py-1 text-[10px] font-bold ${['COMPLETED', 'SUCCESS', 'APPROVED'].includes(deposit.status) ? 'bg-emerald-500/10 text-emerald-300' : deposit.status === 'PENDING' ? 'bg-amber-500/10 text-amber-300' : 'bg-red-500/10 text-red-300'}`}>{deposit.status}</span></td></tr>)}</tbody></table> : <p className="p-5 text-sm text-gray-500">Tài khoản này chưa có giao dịch nạp tiền.</p>}
              </div>
            </div>

            <div className={`${detailTab === 'activity' ? '' : 'hidden'} mt-6 rounded-xl border border-border bg-background p-4`}>
              <p className="text-sm font-semibold text-foreground mb-4">Tổng quan User 360°</p>
              <div className="grid gap-4 md:grid-cols-3">
                {[
                  { label: 'Đơn của Buyer', value: selectedUserDetail?.stats?.buyerOrders ?? '-' },
                  { label: 'Đơn của Seller', value: selectedUserDetail?.stats?.sellerOrders ?? '-' },
                  { label: 'Yêu cầu rút', value: selectedUserDetail?.stats?.withdrawals ?? '-' },
                  { label: 'Khiếu nại', value: selectedUserDetail?.stats?.disputes ?? '-' },
                  { label: 'Ứng dụng Seller', value: selectedUserDetail?.stats?.applications ?? '-' },
                ].map((item, index) => (
                  <div key={index} className="rounded-3xl border border-white/5 bg-card p-4">
                    <p className="text-xs uppercase tracking-[0.2em] text-muted-foreground">{item.label}</p>
                    <p className="mt-3 text-2xl font-bold text-foreground">{item.value}</p>
                  </div>
                ))}
              </div>
            </div>

            <div className={`${detailTab === 'activity' ? '' : 'hidden'} mt-6 grid gap-4 lg:grid-cols-2`}>
              <div className="rounded-3xl border border-border bg-background p-4">
                <p className="text-sm font-semibold text-foreground mb-4">Audit Log gần đây</p>
                <div className="space-y-3 text-sm text-foreground">
                  {selectedUserDetailLoading ? (
                    <p className="text-sm text-muted-foreground">Đang tải dữ liệu...</p>
                  ) : selectedUserDetail?.recentAuditLogs?.length ? selectedUserDetail.recentAuditLogs.map((log: any) => (
                    <div key={log.id} className="rounded-2xl border border-white/5 bg-card p-3">
                      <p className="font-semibold">{log.action}</p>
                      <p className="text-xs text-muted-foreground">{new Date(log.createdAt).toLocaleString('vi-VN')}</p>
                    </div>
                  )) : <p className="text-sm text-muted-foreground">Không có audit logs gần đây.</p>}
                </div>
              </div>
              <div className="rounded-3xl border border-border bg-background p-4">
                <p className="text-sm font-semibold text-foreground mb-4">Thông báo gần đây</p>
                <div className="space-y-3 text-sm text-foreground">
                  {selectedUserDetailLoading ? (
                    <p className="text-sm text-muted-foreground">Đang tải dữ liệu...</p>
                  ) : selectedUserDetail?.recentNotifications?.length ? selectedUserDetail.recentNotifications.map((note: any) => (
                    <div key={note.id} className="rounded-2xl border border-white/5 bg-card p-3">
                      <p className="font-semibold">{note.title}</p>
                      <p className="text-xs text-muted-foreground">{new Date(note.createdAt).toLocaleString('vi-VN')}</p>
                    </div>
                  )) : <p className="text-sm text-muted-foreground">Không có thông báo gần đây.</p>}
                </div>
              </div>
            </div>
            <div className={`${detailTab === 'activity' ? '' : 'hidden'} mt-6 rounded-xl border border-border bg-background p-4`}>
              <p className="text-sm font-semibold text-foreground mb-4">Đơn hàng gần đây</p>
              <div className="space-y-3 text-sm text-foreground">
                {selectedUserDetailLoading ? (
                  <p className="text-sm text-muted-foreground">Đang tải dữ liệu...</p>
                ) : selectedUserDetail?.recentOrders?.length ? selectedUserDetail.recentOrders.map((order: any) => (
                  <div key={order.id} className="rounded-2xl border border-white/5 bg-card p-3">
                    <p className="font-semibold">Đơn #{order.id.slice(0, 8)} - {order.status}</p>
                    <p className="text-xs text-muted-foreground">Người mua: {order.buyer?.name || order.buyer?.email || 'Không có'}</p>
                    <p className="text-xs text-muted-foreground">Người bán: {order.seller?.name || order.seller?.email || 'Không có'}</p>
                  </div>
                )) : <p className="text-sm text-muted-foreground">Không có đơn hàng gần đây.</p>}
              </div>
            </div>
            <div className={`${detailTab === 'activity' ? '' : 'hidden'} mt-6 rounded-xl border border-border bg-background p-4`}>
              <p className="text-sm font-semibold text-foreground mb-4">Yêu cầu rút tiền gần đây</p>
              <div className="space-y-3 text-sm text-foreground">
                {selectedUserDetailLoading ? (
                  <p className="text-sm text-muted-foreground">Đang tải dữ liệu...</p>
                ) : selectedUserDetail?.recentWithdrawals?.length ? selectedUserDetail.recentWithdrawals.map((withdrawal: any) => (
                  <div key={withdrawal.id} className="rounded-2xl border border-white/5 bg-card p-3">
                    <p className="font-semibold">{Number(withdrawal.amount).toLocaleString('vi-VN')}đ</p>
                    <p className="text-xs text-muted-foreground">Trạng thái: {withdrawal.status}</p>
                  </div>
                )) : <p className="text-sm text-muted-foreground">Không có yêu cầu rút tiền gần đây.</p>}
              </div>
            </div>
            <div className={`${detailTab === 'activity' ? '' : 'hidden'} mt-6 rounded-xl border border-border bg-background p-4`}>
              <p className="text-sm font-semibold text-foreground mb-4">Đơn đăng ký Seller gần đây</p>
              <div className="space-y-3 text-sm text-foreground">
                {selectedUserDetailLoading ? (
                  <p className="text-sm text-muted-foreground">Đang tải dữ liệu...</p>
                ) : selectedUserDetail?.recentSellerApplications?.length ? selectedUserDetail.recentSellerApplications.map((app: any) => (
                  <div key={app.id} className="rounded-2xl border border-white/5 bg-card p-3">
                    <p className="font-semibold">{app.shopName}</p>
                    <p className="text-xs text-muted-foreground">Trạng thái: {app.status}</p>
                    <p className="text-xs text-muted-foreground">Ngày tạo: {new Date(app.createdAt).toLocaleDateString('vi-VN')}</p>
                  </div>
                )) : <p className="text-sm text-muted-foreground">Không có hồ sơ đăng ký Seller gần đây.</p>}
              </div>
            </div>

            <div className={`${detailTab === 'profile' ? '' : 'hidden'} flex flex-col sm:flex-row items-center justify-end gap-3 mt-6 border-t border-border pt-4`}>
              <button
                type="button"
                onClick={handleCloseUserModal}
                className="rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-sm text-muted-foreground hover:bg-white/10 transition"
              >
                Hủy
              </button>
              <button
                type="button"
                onClick={handleSaveUser}
                disabled={savingUser}
                className="rounded-xl bg-primary px-4 py-3 text-sm font-semibold text-white hover:bg-primary/90 transition disabled:opacity-50"
              >
                {savingUser ? 'Đang lưu...' : 'Lưu thay đổi'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
