'use client';

import { useEffect, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import Navbar from '@/components/Navbar';
import { api } from '@/lib/api';
import { useAuthStore } from '@/store/authStore';
import { Wallet, ShieldCheck, Building2, Coins, Smartphone, CreditCard, Globe, Info, Activity } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';

interface Transaction {
  id: string;
  type: string;
  amount: string;
  status: string;
  createdAt: string;
  reference?: string | null;
}

interface PaymentProvider {
  code: string;
  name: string;
  enabled: boolean;
  config?: Record<string, any>;
}

export default function WalletPage() {
  const [summary, setSummary] = useState<{ accountBalance: number; lockedBalance: number; sellerBalance: number; pendingBalance: number; escrowBalance: number; totalRevenue: number; totalWithdraw: number; todayRevenue: number; monthlyRevenue: number; accountStatus: string; sellerStatus: string; } | null>(null);
  const [transactions, setTransactions] = useState<Transaction[]>([]);
  const [depositAmount, setDepositAmount] = useState<string>('500000');
  const [usdtAmount, setUsdtAmount] = useState<string>('10');
  const [usdtRate, setUsdtRate] = useState<number>(25000);
  const [activeTab, setActiveTab] = useState<'DEPOSIT' | 'WITHDRAW' | 'TRANSFER' | 'HISTORY'>('DEPOSIT');
  const [paymentMethod, setPaymentMethod] = useState<'BANK' | 'USDT_BEP20' | 'MOMO' | 'CARD' | 'ONLINE'>('BANK');
  const [selectedProvider, setSelectedProvider] = useState<string | null>(null);
  const [providers, setProviders] = useState<PaymentProvider[]>([]);
  const [selectedBank, setSelectedBank] = useState<string>('MBBank');
  const [bankOptions, setBankOptions] = useState<string[]>(['MBBank']);
  const [withdrawAmount, setWithdrawAmount] = useState<string>('');
  const [bankName, setBankName] = useState<string>('');
  const [bankAccount, setBankAccount] = useState<string>('');
  const [accountName, setAccountName] = useState<string>('');
  const [withdrawNote, setWithdrawNote] = useState<string>('');
  const [transferAmount, setTransferAmount] = useState<string>('100000');
  const [transferNote, setTransferNote] = useState<string>('');

  const params = useParams<{ locale?: string }>();
  const router = useRouter();
  const locale = params?.locale || 'vi';

  useEffect(() => {
    fetchWallet();
    api.get('/payment/usdt-rate').then((res) => setUsdtRate(Number(res.data?.rate) || 25000)).catch(() => undefined);
  }, []);

  const fetchBankOptions = async () => {
    try {
      const res = await api.get('/admin/settings/public', { params: { locale } });
      const raw = res.data?.['payment.bankOptions'] || '';
      const list = raw
        .split(',')
        .map((item: string) => item.trim())
        .filter(Boolean);

      if (list.length > 0) {
        setBankOptions(list);
        setSelectedBank((prev) => (list.includes(prev) ? prev : list[0]));
      }
    } catch (error) {
      console.warn('Không thể lấy danh sách ngân hàng từ cấu hình', error);
    }
  };

  const fetchWallet = async () => {
    try {
      const res = await api.get('/wallet/summary');
      setSummary(res.data);
      const historyRes = await api.get('/wallet/history');
      setTransactions(historyRes.data);
    } catch (error) {
      console.error(error);
    }
  };

  const fetchPaymentProviders = async () => {
    try {
      const res = await api.get('/payment/providers');
      const providerData: PaymentProvider[] = res.data || [];
      setProviders(providerData);
      if (providerData.length > 0 && providerData[0].enabled) {
        setSelectedProvider(providerData[0].code);
      }
    } catch (error) {
      console.warn('Không thể lấy danh sách payment provider', error);
    }
  };

  const user = useAuthStore((s) => s.user);
  const roleName = typeof user?.role === 'object' ? user.role?.name : user?.role;
  const isSeller = roleName === 'SELLER';
  const accountBalance = Number(summary?.accountBalance || 0);
  const sellerBalance = Number(summary?.sellerBalance || 0);
  const totalBalance = accountBalance + sellerBalance;

  const handleTransfer = async () => {
    if (!transferAmount || Number(transferAmount) <= 0) return;

    try {
      await api.post('/payment/transfer', {
        fromWallet: 'SELLER',
        toWallet: 'ACCOUNT',
        amount: Number(transferAmount),
        note: transferNote,
      });
      alert('Chuyển tiền giữa ví Seller và Account thành công.');
      setTransferNote('');
      setTransferAmount('100000');
      fetchWallet();
      setActiveTab('HISTORY');
    } catch (error: any) {
      alert(error.response?.data?.message || 'Lỗi khi chuyển tiền giữa ví');
    }
  };

  const handleDeposit = async () => {
    if (paymentMethod === 'USDT_BEP20') {
      if (!usdtAmount || Number(usdtAmount) < 10) {
        alert('Nạp tối thiểu 10 USDT');
        return;
      }
    } else if (!depositAmount || isNaN(Number(depositAmount)) || Number(depositAmount) <= 0) return;
    try {
      const body: Record<string, any> = {
        amount: paymentMethod === 'USDT_BEP20' ? Math.round(Number(usdtAmount) * usdtRate) : Number(depositAmount),
        method: paymentMethod,
      };
      if (paymentMethod === 'USDT_BEP20') body.usdtAmount = Number(usdtAmount);

      if (selectedProvider) {
        body.providerCode = selectedProvider;
      }

      if (paymentMethod === 'BANK') {
        body.bankName = selectedBank;
      }

      const res = await api.post('/payment/deposit', body);
      if (res.data?.sessionId) {
        router.push(`/${locale}/wallet/deposit/${res.data.sessionId}`);
        return;
      }
      if (res.data?.checkoutUrl) {
        window.open(res.data.checkoutUrl, '_blank');
        alert('Đang chuyển sang cổng thanh toán để hoàn tất giao dịch.');
        return;
      }

      fetchWallet();
      alert('Nạp tiền thành công (Sandbox)');
    } catch (error: any) {
      alert(error.response?.data?.message || 'Lỗi nạp tiền');
    }
  };

  const handleWithdraw = async () => {
    if (!withdrawAmount || Number(withdrawAmount) < 100000 || !bankName || !bankAccount || !accountName) return;
    try {
      await api.post('/payment/withdraw', {
        amount: Number(withdrawAmount),
        bankName,
        accountName,
        bankAccount,
        note: withdrawNote
      });
      alert('Tạo yêu cầu rút tiền thành công!');
      fetchWallet();
      setWithdrawAmount('');
      setBankName('');
      setBankAccount('');
      setAccountName('');
      setWithdrawNote('');
      setActiveTab('HISTORY');
    } catch (error: any) {
      alert(error.response?.data?.message || 'Lỗi khi rút tiền');
    }
  };

  const quickAmounts = paymentMethod === 'USDT_BEP20' ? ['10', '20', '50', '100'] : ['50000', '100000', '200000', '500000', '1000000'];

  return (
    <div className="min-h-screen bg-[#0a0a0a] text-foreground font-sans">
      <Navbar />

      <main className="container mx-auto px-4 py-8 max-w-6xl space-y-6">
        {/* Header Widget */}
        <div className="bg-[#141414] border border-white/5 rounded-2xl p-6 md:p-8 flex flex-col md:flex-row justify-between items-start md:items-center relative overflow-hidden">
          <div className="absolute top-0 right-0 w-64 h-64 bg-red-500/10 blur-[100px] pointer-events-none rounded-full" />

          <div className="z-10 space-y-2">
            <h1 className="text-2xl md:text-3xl font-bold text-white flex items-center gap-3">
              Ví của bạn
            </h1>
            <p className="text-gray-400 text-sm md:text-base max-w-md">
              Quản lý số dư, nạp rút và theo dõi mọi giao dịch một cách dễ dàng.
            </p>
          </div>

          <div className="z-10 mt-6 md:mt-0 flex items-center gap-6">
            <div className="text-right">
              <p className="text-red-500 text-xs font-semibold mb-1 flex items-center justify-end gap-1">
                Tổng số dư ước tính <span className="w-1.5 h-1.5 rounded-full bg-red-500 animate-pulse"></span>
              </p>
              <h2 className="text-3xl md:text-4xl font-bold text-white">
                {Number((summary?.accountBalance || 0) + (summary?.sellerBalance || 0)).toLocaleString('vi-VN')} <span className="text-xl underline decoration-1 underline-offset-4">đ</span>
              </h2>
              <p className="text-gray-500 text-sm mt-1 font-medium">≈ {(((summary?.accountBalance || 0) + (summary?.sellerBalance || 0)) / 25000).toFixed(2)} US$</p>
            </div>
            {/* 3D Wallet Icon Placeholder (Can use an image here) */}
            <div className="hidden md:flex w-24 h-24 bg-gradient-to-br from-red-500 to-red-700 rounded-2xl shadow-[0_0_30px_rgba(239,68,68,0.3)] transform rotate-12 items-center justify-center border border-red-400/50 relative">
               <Wallet className="w-10 h-10 text-white transform -rotate-12" />
               <div className="absolute -top-2 -right-2 w-6 h-6 bg-yellow-400 rounded-full shadow-lg border-2 border-[#141414] animate-bounce"></div>
               <div className="absolute -bottom-2 -left-2 w-4 h-4 bg-yellow-500 rounded-full shadow-lg border-2 border-[#141414]"></div>
            </div>
          </div>
        </div>

        {/* Main Workspace */}
        <div className="bg-[#141414] border border-white/5 rounded-2xl p-6 md:p-8 space-y-8">

          {/* Tabs */}
          <div className="flex items-center gap-6 border-b border-white/5 pb-4">
            <button
              onClick={() => setActiveTab('DEPOSIT')}
              className={`text-sm font-semibold pb-4 -mb-[17px] transition-colors ${activeTab === 'DEPOSIT' ? 'text-white border-b-2 border-red-500' : 'text-gray-400 hover:text-gray-200'}`}
            >
              Nạp tiền
            </button>
            {isSeller && (
              <button
                onClick={() => setActiveTab('WITHDRAW')}
                className={`text-sm font-semibold pb-4 -mb-[17px] transition-colors ${activeTab === 'WITHDRAW' ? 'text-white border-b-2 border-red-500' : 'text-gray-400 hover:text-gray-200'}`}
              >
                Rút tiền
              </button>
            )}
            <button
              onClick={() => setActiveTab('TRANSFER')}
              className={`text-sm font-semibold pb-4 -mb-[17px] transition-colors ${activeTab === 'TRANSFER' ? 'text-white border-b-2 border-red-500' : 'text-gray-400 hover:text-gray-200'}`}
            >
              Chuyển ví
            </button>
            <button
              onClick={() => setActiveTab('HISTORY')}
              className={`text-sm font-semibold pb-4 -mb-[17px] transition-colors ${activeTab === 'HISTORY' ? 'text-white border-b-2 border-red-500' : 'text-gray-400 hover:text-gray-200'}`}
            >
              Lịch sử
            </button>
          </div>

          {activeTab === 'DEPOSIT' && (
            <div className="space-y-8 animate-in fade-in slide-in-from-bottom-2 duration-500">
              {/* Stepper */}
              <div className="flex items-center justify-between max-w-2xl mx-auto py-4">
                <div className="flex flex-col items-center gap-2">
                  <div className="w-6 h-6 rounded-full bg-red-500 text-white flex items-center justify-center text-xs font-bold">1</div>
                  <span className="text-red-500 text-xs font-semibold">Cách nạp</span>
                </div>
                <div className="flex-1 h-px bg-white/10 mx-4"></div>
                <div className="flex flex-col items-center gap-2 opacity-50">
                  <div className="w-6 h-6 rounded-full bg-white/10 text-white flex items-center justify-center text-xs font-bold">2</div>
                  <span className="text-gray-400 text-xs font-semibold">Số tiền</span>
                </div>
                <div className="flex-1 h-px bg-white/10 mx-4"></div>
                <div className="flex flex-col items-center gap-2 opacity-50">
                  <div className="w-6 h-6 rounded-full bg-white/10 text-white flex items-center justify-center text-xs font-bold">3</div>
                  <span className="text-gray-400 text-xs font-semibold">Chuyển khoản</span>
                </div>
              </div>

              {/* Payment Methods */}
              <div className="space-y-4">
                <h3 className="text-white font-semibold">Chọn cách nạp</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <button
                    onClick={() => setPaymentMethod('BANK')}
                    className={`p-4 rounded-xl border text-left transition-all ${paymentMethod === 'BANK' ? 'bg-red-500/5 border-red-500/50 ring-1 ring-red-500/50' : 'bg-white/5 border-white/5 hover:border-white/10'}`}
                  >
                    <Building2 className={`w-6 h-6 mb-3 ${paymentMethod === 'BANK' ? 'text-red-500' : 'text-gray-400'}`} />
                    <h4 className={`text-sm font-bold ${paymentMethod === 'BANK' ? 'text-white' : 'text-gray-300'}`}>Chuyển khoản ngân hàng</h4>
                    <p className="text-xs text-gray-500 mt-1">Ưu tiên</p>
                  </button>

                  <button
                    onClick={() => setPaymentMethod('USDT_BEP20')}
                    style={{ display: 'none' }}
                    className={`p-4 rounded-xl border text-left transition-all ${paymentMethod === 'MOMO' ? 'bg-red-500/5 border-red-500/50 ring-1 ring-red-500/50' : 'bg-white/5 border-white/5 hover:border-white/10'}`}
                  >
                    <Smartphone className={`w-6 h-6 mb-3 ${paymentMethod === 'MOMO' ? 'text-red-500' : 'text-gray-400'}`} />
                    <h4 className={`text-sm font-bold ${paymentMethod === 'MOMO' ? 'text-white' : 'text-gray-300'}`}>Ví điện tử</h4>
                    <p className="text-xs text-gray-500 mt-1">MoMo / ZaloPay</p>
                  </button>

                  <button
                    onClick={() => setPaymentMethod('BANK')}
                    style={{ display: 'none' }}
                    className={`p-4 rounded-xl border text-left transition-all ${paymentMethod === 'CARD' ? 'bg-red-500/5 border-red-500/50 ring-1 ring-red-500/50' : 'bg-white/5 border-white/5 hover:border-white/10'}`}
                  >
                    <CreditCard className={`w-6 h-6 mb-3 ${paymentMethod === 'CARD' ? 'text-red-500' : 'text-gray-400'}`} />
                    <h4 className={`text-sm font-bold ${paymentMethod === 'CARD' ? 'text-white' : 'text-gray-300'}`}>Nạp qua thẻ cào</h4>
                    <p className="text-xs text-gray-500 mt-1">Thẻ cào / Thẻ game</p>
                  </button>

                  <button
                    onClick={() => setPaymentMethod('USDT_BEP20')}
                    className={`p-4 rounded-xl border text-left transition-all ${paymentMethod === 'USDT_BEP20' ? 'bg-red-500/5 border-red-500/50 ring-1 ring-red-500/50' : 'bg-white/5 border-white/5 hover:border-white/10'}`}
                  >
                    <Coins className={`w-6 h-6 mb-3 ${paymentMethod === 'USDT_BEP20' ? 'text-red-500' : 'text-gray-400'}`} />
                    <h4 className={`text-sm font-bold ${paymentMethod === 'USDT_BEP20' ? 'text-white' : 'text-gray-300'}`}>USDT BEP20</h4>
                    <p className="text-xs text-gray-500 mt-1">Mạng BNB Smart Chain</p>
                  </button>
                </div>
              </div>

              {false && providers.length > 0 && (
                <div className="space-y-4">
                  <h3 className="text-white font-semibold">Chọn cổng thanh toán</h3>
                  <select
                    value={selectedProvider || ''}
                    onChange={(e) => setSelectedProvider(e.target.value)}
                    className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-3 text-white focus:outline-none"
                  >
                    <option value="">Tự động chọn cổng</option>
                    {providers.map((provider) => (
                      <option key={provider.code} value={provider.code} disabled={!provider.enabled}>
                        {provider.name} {provider.enabled ? '' : '(Tạm tắt)'}
                      </option>
                    ))}
                  </select>
                </div>
              )}

              {false && paymentMethod === 'BANK' && (
                <div className="space-y-4">
                  <h3 className="text-white font-semibold">Chọn ngân hàng chuyển khoản</h3>
                  <select
                    value={selectedBank}
                    onChange={(e) => setSelectedBank(e.target.value)}
                    className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-3 text-white focus:outline-none"
                  >
                    {bankOptions.map((bank) => (
                      <option key={bank} value={bank}>
                        {bank}
                      </option>
                    ))}
                  </select>
                  <p className="text-gray-400 text-sm">Ngân hàng này sẽ hiện rõ trong thông tin chuyển khoản.</p>
                </div>
              )}

              {/* Amount Selection */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-8 items-end">
                <div className="space-y-3">
                  <label className="text-white font-semibold text-sm">{paymentMethod === 'USDT_BEP20' ? 'Số tiền USDT' : 'Số tiền (VND)'}</label>
                  <div className="relative">
                    <Input
                      type="number"
                      value={paymentMethod === 'USDT_BEP20' ? usdtAmount : depositAmount}
                      onChange={(e) => paymentMethod === 'USDT_BEP20' ? setUsdtAmount(e.target.value) : setDepositAmount(e.target.value)}
                      className="bg-black border-white/10 h-12 text-white pl-4 font-medium"
                    />
                  </div>
                </div>

                <div className="space-y-3">
                  <label className="text-white font-semibold text-sm">Chọn nhanh</label>
                  <div className="flex flex-wrap gap-2">
                    {quickAmounts.map(amt => (
                      <button
                        key={amt}
                        onClick={() => paymentMethod === 'USDT_BEP20' ? setUsdtAmount(amt) : setDepositAmount(amt)}
                        className={`px-4 py-2.5 rounded-lg border text-sm font-bold transition-all ${
                          (paymentMethod === 'USDT_BEP20' ? usdtAmount : depositAmount) === amt
                          ? 'border-red-500 text-red-500 bg-red-500/10'
                          : 'border-white/10 text-gray-400 hover:border-white/30 hover:text-white bg-black'
                        }`}
                      >
                        {Number(amt).toLocaleString('vi-VN')}{paymentMethod === 'USDT_BEP20' ? ' USDT' : ' đ'}
                      </button>
                    ))}
                  </div>
                </div>
              </div>
              {paymentMethod === 'USDT_BEP20' && (
                <p className="text-sm text-amber-200">Tỷ giá thị trường: 1 USDT ≈ {usdtRate.toLocaleString('vi-VN')} đ · Quy đổi: {(Number(usdtAmount || 0) * usdtRate).toLocaleString('vi-VN')} đ · Tối thiểu 10 USDT</p>
              )}

              {/* Actions */}
              <div className="flex items-center gap-4 pt-4 border-t border-white/5">
                <Button
                  onClick={handleDeposit}
                  className="bg-red-500 hover:bg-red-600 text-white font-bold px-8 py-6 rounded-xl shadow-[0_0_20px_rgba(239,68,68,0.2)] hover:shadow-[0_0_30px_rgba(239,68,68,0.4)] transition-all"
                >
                  Tạo phiên chuyển khoản
                </Button>
                <div className="flex items-center gap-2 text-gray-400 text-sm">
                  <ShieldCheck className="w-4 h-4 text-green-500" />
                  Giao dịch được mã hóa và bảo mật tuyệt đối.
                </div>
              </div>

            </div>
          )}

          {activeTab === 'TRANSFER' && (
            <div className="space-y-6 animate-in fade-in duration-500 max-w-2xl mx-auto bg-[#141414] p-6 rounded-3xl border border-white/10">
              <h2 className="text-xl font-bold text-white">Chuyển tiền giữa ví</h2>
              <p className="text-sm text-gray-400">Chỉ cho phép chuyển từ ví Seller sang ví Account.</p>

              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-semibold text-white mb-2">Từ ví</label>
                  <div className="rounded-xl bg-black/50 border border-white/10 px-4 py-3 text-white">
                    Wallet Seller ({sellerBalance.toLocaleString('vi-VN')} đ)
                  </div>
                </div>
                <div>
                  <label className="block text-sm font-semibold text-white mb-2">Đến ví</label>
                  <div className="rounded-xl bg-black/50 border border-white/10 px-4 py-3 text-white">
                    Wallet Account ({accountBalance.toLocaleString('vi-VN')} đ)
                  </div>
                </div>
              </div>

              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-semibold text-white mb-2">Số tiền cần chuyển</label>
                  <Input
                    type="number"
                    value={transferAmount}
                    onChange={(e) => setTransferAmount(e.target.value)}
                    className="w-full bg-black/50 border-white/10 text-white"
                  />
                </div>
                <div>
                  <label className="block text-sm font-semibold text-white mb-2">Ghi chú</label>
                  <textarea
                    value={transferNote}
                    onChange={(e) => setTransferNote(e.target.value.slice(0, 120))}
                    className="w-full min-h-[120px] bg-black/50 border border-white/10 rounded-xl p-4 text-white placeholder-gray-400 focus:outline-none"
                    placeholder="Ghi chú cho chuyển ví (tuỳ chọn)"
                  />
                  <p className="text-xs text-gray-500 mt-2">{transferNote.length}/120 ký tự</p>
                </div>
              </div>

              <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between pt-3 border-t border-white/10">
                <div className="text-sm text-gray-400">
                  Số dư nguồn: <span className="font-semibold text-white">{sellerBalance.toLocaleString('vi-VN')} đ</span>
                </div>
                <Button
                  onClick={handleTransfer}
                  className="bg-red-500 hover:bg-red-600 text-white font-bold px-8 py-4 rounded-xl transition-all"
                >
                  Chuyển từ Seller sang Account
                </Button>
              </div>
            </div>
          )}

          {activeTab === 'WITHDRAW' && (
            <div className="space-y-6 animate-in fade-in duration-500 max-w-lg mx-auto bg-[#141414]">
              {!isSeller ? (
                <div className="rounded-3xl border border-white/10 bg-[#111111] p-10 text-center">
                  <ShieldCheck className="mx-auto mb-4 w-14 h-14 text-orange-400" />
                  <h2 className="text-2xl font-bold text-white">Rút tiền chỉ dành cho Seller</h2>
                  <p className="mt-3 text-gray-400">
                    Tài khoản hiện tại của bạn chưa có quyền Seller, vì vậy chức năng rút tiền sẽ bị khoá.
                  </p>
                  <button
                    onClick={() => setActiveTab('DEPOSIT')}
                    className="mt-6 inline-flex items-center justify-center rounded-xl bg-red-500 px-6 py-3 text-sm font-bold text-white hover:bg-red-600 transition-colors"
                  >
                    Quay về Nạp tiền
                  </button>
                </div>
              ) : (
                <>
                  <h2 className="text-xl font-bold text-white">Tạo yêu cầu rút</h2>

                  {/* Currency */}
                  <div className="space-y-2">
                    <label className="text-white font-bold text-sm">Tiền tệ</label>
                    <div>
                      <select className="bg-white/5 border border-white/10 rounded-lg px-4 py-2 text-white text-sm focus:outline-none appearance-none cursor-pointer pr-8 bg-[url('data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%239ca3af%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpolyline%20points%3D%226%209%2012%2015%2018%209%22%3E%3C%2Fpolyline%3E%3C%2Fsvg%3E')] bg-[length:1em] bg-[right_0.5rem_center] bg-no-repeat">
                        <option value="VND">VND</option>
                      </select>
                    </div>
                  </div>
              {/* Receiving Account */}
              <div className="space-y-3">
                <label className="text-white font-bold text-sm">Tài khoản nhận</label>
                <div className="bg-black/40 border border-white/10 rounded-xl p-5 space-y-4">
                  <div className="flex items-start gap-4">
                    <div className="w-10 h-10 rounded-lg bg-orange-500/10 border border-orange-500/20 flex items-center justify-center shrink-0">
                      <Wallet className="w-5 h-5 text-orange-500" />
                    </div>
                    <div className="space-y-1 w-full">
                      <h4 className="text-white font-bold">Tên ngân hàng</h4>
                      <p className="text-gray-400 text-sm">Tên chủ tài khoản</p>
                      <div className="inline-block px-3 py-1 bg-orange-500/20 text-orange-500 text-xs font-bold rounded-full mt-1">
                        Thiếu thông tin
                      </div>
                    </div>
                  </div>

                  <div className="space-y-3 pt-2">
                    <Input
                      placeholder="Tên ngân hàng"
                      value={bankName}
                      onChange={(e) => setBankName(e.target.value)}
                      className="bg-black border-white/10 text-white placeholder-gray-500"
                    />
                    <Input
                      placeholder="Tên chủ tài khoản"
                      value={accountName}
                      onChange={(e) => setAccountName(e.target.value)}
                      className="bg-black border-white/10 text-white placeholder-gray-500"
                    />
                    <Input
                      placeholder="Số tài khoản"
                      value={bankAccount}
                      onChange={(e) => setBankAccount(e.target.value)}
                      className="bg-black border-white/10 text-white placeholder-gray-500"
                    />
                  </div>
                </div>

                <p className="text-gray-400 text-xs font-medium">
                  Thông tin này sẽ được lưu cùng yêu cầu rút sau khi bạn gửi.
                </p>

                <button className="flex items-center justify-center gap-2 w-full py-3 text-sm font-bold text-white hover:bg-white/5 rounded-lg transition-colors mt-2">
                  <span className="text-lg leading-none">+</span> Nhập tài khoản nhận khác
                </button>
              </div>

              {/* Note */}
              <div className="space-y-2">
                <label className="text-white font-bold text-sm">Ghi chú (tùy chọn)</label>
                <div className="relative">
                  <textarea
                    rows={3}
                    value={withdrawNote}
                    onChange={(e) => setWithdrawNote(e.target.value.slice(0, 120))}
                    placeholder="Nhập ghi chú cho yêu cầu rút..."
                    className="w-full bg-black/40 border border-white/10 rounded-xl p-4 text-white placeholder-gray-500 text-sm focus:outline-none resize-none"
                  />
                  <div className="absolute bottom-3 right-3 text-gray-500 text-xs font-medium">
                    {withdrawNote.length}/120
                  </div>
                </div>
              </div>

              {/* Summary Box */}
              <div className="bg-black/40 border border-white/10 rounded-xl p-5 space-y-3">
                <div className="flex justify-between items-center text-sm">
                  <span className="text-white font-bold">Tạm tính</span>
                  <span className="text-white font-bold">{Number(withdrawAmount || 0).toLocaleString('vi-VN')} đ</span>
                </div>
                <div className="flex justify-between items-center text-sm">
                  <span className="text-white font-bold">Phí xử lý</span>
                  <span className="text-white font-bold">-0 đ</span>
                </div>
                <div className="flex justify-between items-center text-sm">
                  <span className="text-white font-bold">Phí chuyển khoản</span>
                  <span className="text-white font-bold">-0 đ</span>
                </div>

                <div className="h-px bg-white/10 my-3"></div>

                <div className="flex justify-between items-center">
                  <span className="text-white font-bold">Số tiền nhận ước tính</span>
                  <span className="text-red-500 font-bold text-lg">{Number(withdrawAmount || 0).toLocaleString('vi-VN')} đ</span>
                </div>
              </div>

              {/* Submit */}
              <button
                onClick={handleWithdraw}
                disabled={!withdrawAmount || Number(withdrawAmount) < 100000 || !bankName || !bankAccount || !accountName}
                className="w-full bg-red-600 hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed text-white font-bold py-4 rounded-xl transition-all flex items-center justify-center gap-2 mt-4"
              >
                <ShieldCheck className="w-5 h-5" /> Gửi yêu cầu rút
              </button>
                </>
              )}
            </div>
          )}

          {activeTab === 'HISTORY' && (
            <div className="space-y-4 animate-in fade-in duration-500">
               {transactions.length === 0 ? (
                <div className="flex flex-col items-center justify-center py-20 text-gray-500">
                  <Activity className="w-12 h-12 mb-4 opacity-20" />
                  <p>Chưa có giao dịch nào</p>
                </div>
              ) : (
                <div className="space-y-2">
                  {transactions.map((tx) => (
                    <div key={tx.id} className="flex items-center justify-between gap-4 p-4 rounded-xl bg-black/40 border border-white/5 hover:bg-white/5 transition-colors">
                      <div className="flex items-center gap-4">
                        <div className={`w-10 h-10 rounded-full flex items-center justify-center ${
                          tx.type === 'DEPOSIT' || tx.type === 'ESCROW_RELEASE' ? 'bg-green-500/10 text-green-500' : 'bg-red-500/10 text-red-500'
                        }`}>
                          <Wallet className="w-5 h-5" />
                        </div>
                        <div>
                          <p className="text-white font-semibold text-sm">
                            {tx.type === 'DEPOSIT' ? 'Nạp tiền vào ví' : tx.type === 'PAYMENT' ? 'Thanh toán đơn hàng' : tx.type === 'ESCROW_RELEASE' ? 'Nhận tiền bán hàng' : tx.type}
                          </p>
                          <p className="text-gray-500 text-xs mt-1">{new Date(tx.createdAt).toLocaleString('vi-VN')}</p>
                        </div>
                      </div>
                      <div className="flex shrink-0 items-center gap-3 text-right">
                        {tx.type === 'DEPOSIT' && tx.reference?.startsWith('PAYMENT_SESSION_') && (
                          <button
                            type="button"
                            onClick={() => router.push(`/${locale}/wallet/deposit/${tx.reference!.replace('PAYMENT_SESSION_', '')}`)}
                            className="rounded-lg border border-white/10 px-3 py-2 text-xs font-semibold text-zinc-300 transition hover:border-rose-400/50 hover:text-white"
                          >
                            Xem phiên nạp
                          </button>
                        )}
                        <p className={`font-bold ${
                          tx.type === 'DEPOSIT' || tx.type === 'ESCROW_RELEASE' ? 'text-green-500' : 'text-red-500'
                        }`}>
                          {tx.type === 'DEPOSIT' || tx.type === 'ESCROW_RELEASE' ? '+' : '-'}{Number(tx.amount).toLocaleString('vi-VN')} đ
                        </p>
                        <span className={`text-[10px] font-bold px-2 py-0.5 rounded uppercase mt-1 inline-block ${
                          tx.status === 'COMPLETED' ? 'bg-green-500/20 text-green-500 border border-green-500/20' : tx.status === 'PENDING' ? 'bg-yellow-500/20 text-yellow-500' : 'bg-red-500/20 text-red-500'
                        }`}>
                          {tx.status}
                        </span>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

        </div>

        {/* Bottom Widgets Grid */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          {/* VND Box */}
          <div className="bg-[#1a1515] border border-red-500/10 rounded-2xl p-6 space-y-4 hover:border-red-500/30 transition-all">
            <div className="flex justify-between items-start">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-lg bg-red-500/10 flex items-center justify-center border border-red-500/20">
                   <Wallet className="w-5 h-5 text-red-500" />
                </div>
                <div>
                  <p className="text-gray-400 text-xs font-medium">Số dư VND</p>
                  <p className="text-white font-bold text-lg">{totalBalance.toLocaleString('vi-VN')} đ</p>
                </div>
              </div>
              <span className="bg-green-500/10 text-green-500 text-[10px] font-bold px-2 py-1 rounded border border-green-500/20 uppercase">Khả dụng</span>
            </div>
            <div className="grid grid-cols-3 gap-2">
              <button onClick={() => setActiveTab('DEPOSIT')} className="bg-black hover:bg-white/5 text-gray-300 text-xs font-semibold py-2 rounded-lg transition-colors border border-white/5">Nạp tiền</button>
              {isSeller ? (
                <button onClick={() => setActiveTab('WITHDRAW')} className="bg-black hover:bg-white/5 text-gray-300 text-xs font-semibold py-2 rounded-lg transition-colors border border-white/5">Rút tiền</button>
              ) : (
                <button disabled className="bg-black text-gray-600 text-xs font-semibold py-2 rounded-lg opacity-50 cursor-not-allowed border border-white/5">Rút tiền</button>
              )}
              <button onClick={() => setActiveTab('HISTORY')} className="bg-black hover:bg-white/5 text-gray-300 text-xs font-semibold py-2 rounded-lg transition-colors border border-white/5">Lịch sử</button>
            </div>
          </div>

          {/* USD Box */}
          <div className="bg-[#151a17] border border-green-500/10 rounded-2xl p-6 space-y-4 hover:border-green-500/30 transition-all">
            <div className="flex justify-between items-start">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-lg bg-green-500/10 flex items-center justify-center border border-green-500/20">
                   <span className="text-green-500 font-bold">$</span>
                </div>
                <div>
                  <p className="text-gray-400 text-xs font-medium">Số dư USD</p>
                  <p className="text-white font-bold text-lg">{(totalBalance / 25000).toFixed(2)} US$</p>
                </div>
              </div>
              <span className="bg-green-500/10 text-green-500 text-[10px] font-bold px-2 py-1 rounded border border-green-500/20 uppercase">Khả dụng</span>
            </div>
            <div className="grid grid-cols-3 gap-2">
              <button onClick={() => setActiveTab('DEPOSIT')} className="bg-black hover:bg-white/5 text-gray-300 text-xs font-semibold py-2 rounded-lg transition-colors border border-white/5">Nạp USD</button>
              <button onClick={() => setActiveTab('WITHDRAW')} className="bg-black hover:bg-white/5 text-gray-300 text-xs font-semibold py-2 rounded-lg transition-colors border border-white/5">Rút USD</button>
              <button disabled className="bg-black text-gray-500 text-xs font-semibold py-2 rounded-lg opacity-50 cursor-not-allowed border border-white/5">Liên hệ hỗ trợ</button>
            </div>
          </div>

          {/* Overview Box */}
          <div className="bg-[#141414] border border-white/5 rounded-2xl p-6 flex flex-col justify-between hover:border-white/10 transition-all">
            <div className="flex justify-between items-center mb-4">
              <h3 className="text-white font-bold text-sm">Tổng quan tháng 5/2026</h3>
              <span className="text-gray-500 text-xs bg-white/5 px-2 py-1 rounded">tháng 6 năm 2026</span>
            </div>

            <div className="grid grid-cols-3 gap-4 mb-6">
              <div>
                <p className="text-gray-400 text-[10px] mb-1">Tổng nạp</p>
                <p className="text-white font-bold text-sm">0 đ</p>
                <p className="text-green-500 text-[10px] mt-1">0% so với tháng trước</p>
              </div>
              <div>
                <p className="text-gray-400 text-[10px] mb-1">Tổng chi tiêu</p>
                <p className="text-white font-bold text-sm">0 đ</p>
                <p className="text-green-500 text-[10px] mt-1">0% so với tháng trước</p>
              </div>
              <div>
                <p className="text-gray-400 text-[10px] mb-1">Số giao dịch</p>
                <p className="text-white font-bold text-sm">0</p>
                <p className="text-green-500 text-[10px] mt-1">0 so với tháng trước</p>
              </div>
            </div>

            {/* Progress Bar line */}
            <div className="w-full flex items-center gap-1 relative">
               <div className="w-2 h-2 rounded-full bg-orange-500 z-10 absolute left-0"></div>
               <div className="w-full h-[2px] bg-gradient-to-r from-orange-500 to-orange-500/20"></div>
               <div className="w-2 h-2 rounded-full bg-orange-500/50 z-10 absolute right-0"></div>
            </div>
          </div>
        </div>

      </main>
    </div>
  );
}
