import React, { useState, useEffect } from 'react';
import { t } from '@/i18n';
import { getBalance, getTransactions } from '../../services/wallet';
import type { WalletBalance, TransactionRecord } from '../../services/wallet';
// Taro mini-program component

/**
 * P2. 钱包页面 (只读)
 *
 * 余额展示 + 交易记录，无充值/提现操作
 */

const txIconMap: Record<string, string> = {
  buy: '\uD83D\uDED2',
  sell: '\uD83D\uDCB0',
  deposit: '\u2795',
  withdraw: '\uD83C\uDFE6',
  transfer: '\uD83C\uDF81',
  redeem: '\u2705',
};

const txColorMap: Record<string, string> = {
  buy: '#6C5CE7',
  sell: '#00C48C',
  deposit: '#3498DB',
  withdraw: '#E74C3C',
  transfer: '#FF9500',
  redeem: '#A0A8BE',
};

const WalletPage: React.FC = () => {
  const [balance, setBalance] = useState<WalletBalance | null>(null);
  const [transactions, setTransactions] = useState<TransactionRecord[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    Promise.all([
      getBalance().catch(() => null),
      getTransactions().catch(() => ({ items: [], total: 0 })),
    ]).then(([balanceData, txData]) => {
      if (balanceData) setBalance(balanceData);
      setTransactions(txData?.items || []);
    }).finally(() => setLoading(false));
  }, []);

  const formatTime = (dateStr: string) => {
    if (!dateStr) return '';
    try {
      const date = new Date(dateStr);
      const now = new Date();
      if (date.toDateString() === now.toDateString()) {
        return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }) + ' today';
      }
      return `${String(date.getMonth() + 1).padStart(2, '0')}/${String(date.getDate()).padStart(2, '0')}`;
    } catch {
      return dateStr;
    }
  };

  return (
    <view className="wallet-page">
      {/* Balance Card */}
      <view className="wallet-balance-card">
        <text className="wallet-balance-label">{t('wallet_total_balance')}</text>
        <text className="wallet-balance-amount">
          {loading ? '...' : `$${(balance?.total ?? 0).toLocaleString('en-US', { minimumFractionDigits: 2 })}`}
        </text>
        <view className="wallet-sub-row">
          <view className="wallet-sub-item">
            <text className="wallet-sub-label">{t('wallet_available')}</text>
            <text className="wallet-sub-value">
              {loading ? '...' : `$${(balance?.available ?? 0).toLocaleString('en-US', { minimumFractionDigits: 2 })}`}
            </text>
          </view>
          <view className="wallet-sub-divider" />
          <view className="wallet-sub-item">
            <text className="wallet-sub-label">{t('wallet_frozen')}</text>
            <text className="wallet-sub-value">
              {loading ? '...' : `$${(balance?.frozen ?? 0).toLocaleString('en-US', { minimumFractionDigits: 2 })}`}
            </text>
          </view>
        </view>
      </view>

      {/* Notice Bar */}
      <view className="wallet-notice">
        <text className="wallet-notice-icon">ℹ️</text>
        <text className="wallet-notice-text">{t('wallet_read_only_hint')}</text>
        <text className="wallet-notice-link">{t('download_btn')}</text>
      </view>

      {/* Transaction Records */}
      <view className="wallet-records-section">
        <view className="wallet-records-header">
          <text className="wallet-records-title">{t('wallet_records')}</text>
          <text className="wallet-records-filter">{t('wallet_filter')}</text>
        </view>

        <view className="wallet-records-list">
          {loading ? (
            <view style={{ textAlign: 'center', padding: '40rpx 0' }}>
              <text style={{ color: '#A0A8BE', fontSize: '26rpx' }}>{t('loading') || '加载中...'}</text>
            </view>
          ) : transactions.length === 0 ? (
            <view style={{ textAlign: 'center', padding: '40rpx 0' }}>
              <text style={{ color: '#A0A8BE', fontSize: '26rpx' }}>{t('empty') || '暂无记录'}</text>
            </view>
          ) : (
            transactions.map((tx, i) => {
              const isPositive = tx.amount > 0;
              const color = txColorMap[tx.type] || '#A0A8BE';
              const icon = txIconMap[tx.type] || '\uD83D\uDD04';

              return (
                <view key={tx.id}>
                  <view className="wallet-tx-item">
                    <view className="wallet-tx-icon" style={{ background: color }}>
                      <text className="wallet-tx-emoji">{icon}</text>
                    </view>
                    <view className="wallet-tx-info">
                      <text className="wallet-tx-title">{tx.description}</text>
                      <text className="wallet-tx-time">{formatTime(tx.createdAt)}</text>
                    </view>
                    <text
                      className="wallet-tx-amount"
                      style={{ color: isPositive ? '#00C48C' : '#141723' }}
                    >
                      {isPositive ? '+' : ''}¥{Math.abs(tx.amount).toFixed(2)}
                    </text>
                  </view>
                  {i < transactions.length - 1 && <view className="wallet-tx-divider" />}
                </view>
              );
            })
          )}
        </view>
      </view>
    </view>
  );
};

export default WalletPage;

/*
CSS:

.wallet-page { background: #F8F9FC; min-height: 100vh; padding-bottom: 60rpx; }

.wallet-balance-card {
  margin: 32rpx; padding: 40rpx 32rpx;
  background: linear-gradient(135deg, #6C5CE7, #4834D4);
  border-radius: 24rpx;
}
.wallet-balance-label { font-size: 26rpx; color: rgba(255,255,255,0.7); }
.wallet-balance-amount {
  display: block; font-size: 56rpx; font-weight: 700; color: white;
  margin-top: 12rpx;
}
.wallet-sub-row {
  display: flex; align-items: center; margin-top: 28rpx;
  padding-top: 24rpx; border-top: 1rpx solid rgba(255,255,255,0.2);
}
.wallet-sub-item { flex: 1; }
.wallet-sub-label { font-size: 22rpx; color: rgba(255,255,255,0.6); }
.wallet-sub-value { display: block; font-size: 30rpx; font-weight: 600; color: white; margin-top: 4rpx; }
.wallet-sub-divider {
  width: 1rpx; height: 48rpx; background: rgba(255,255,255,0.2);
  margin: 0 32rpx;
}

.wallet-notice {
  display: flex; align-items: center; margin: 0 32rpx 24rpx;
  padding: 16rpx 20rpx; background: #FFF9E6;
  border-radius: 12rpx; border: 1rpx solid #FFE8A3;
}
.wallet-notice-icon { font-size: 28rpx; margin-right: 10rpx; }
.wallet-notice-text { flex: 1; font-size: 24rpx; color: #8B6914; }
.wallet-notice-link { font-size: 24rpx; color: #6C5CE7; font-weight: 500; }

.wallet-records-section {
  margin: 0 32rpx; background: white; border-radius: 20rpx;
  overflow: hidden; border: 1rpx solid #F1F3F8;
}
.wallet-records-header {
  display: flex; align-items: center; justify-content: space-between;
  padding: 24rpx 24rpx 16rpx;
}
.wallet-records-title { font-size: 30rpx; font-weight: 600; color: #141723; }
.wallet-records-filter { font-size: 24rpx; color: #6C5CE7; }

.wallet-records-list { padding: 0 24rpx; }
.wallet-tx-item {
  display: flex; align-items: center; padding: 20rpx 0;
}
.wallet-tx-icon {
  width: 64rpx; height: 64rpx; border-radius: 50%;
  display: flex; align-items: center; justify-content: center;
  flex-shrink: 0;
}
.wallet-tx-emoji { font-size: 28rpx; }
.wallet-tx-info { flex: 1; margin-left: 18rpx; }
.wallet-tx-title { font-size: 28rpx; color: #141723; font-weight: 500; }
.wallet-tx-time { display: block; font-size: 22rpx; color: #A0A8BE; margin-top: 4rpx; }
.wallet-tx-amount { font-size: 30rpx; font-weight: 600; flex-shrink: 0; }
.wallet-tx-divider { height: 1rpx; background: #F1F3F8; margin-left: 82rpx; }
*/
