'use client';

import React, { useState } from 'react';
import { t } from '@/i18n/locales';
import { useApi } from '@/lib/use-api';

/**
 * D4. 交易监控
 *
 * 实时交易流、交易统计、订单管理
 */

interface TradingStats {
  todayVolume: number;
  todayAmount: number;
  avgDiscount: number;
  largeTrades: number;
}

interface Order {
  orderId: string;
  type: string;
  couponName: string;
  buyer: string;
  seller: string;
  amount: number;
  status: string;
  time: string;
}

interface OrdersResponse {
  items: Order[];
  total: number;
}

const loadingBox: React.CSSProperties = {
  display: 'flex', alignItems: 'center', justifyContent: 'center',
  padding: 40, color: 'var(--color-text-tertiary)', font: 'var(--text-body)',
};

export const TradingMonitorPage: React.FC = () => {
  const [page] = useState(1);
  const [limit] = useState(20);

  const { data: statsData, isLoading: statsLoading } = useApi<TradingStats>('/api/v1/admin/trades/stats');
  const { data: ordersData, isLoading: ordersLoading, error } = useApi<OrdersResponse>('/api/v1/admin/trades/orders', {
    params: { page, limit },
  });

  const tradingStats = statsData ? [
    { label: t('trading_today_volume'), value: statsData.todayVolume?.toLocaleString() ?? '0', color: 'var(--color-primary)' },
    { label: t('trading_today_amount'), value: `$${statsData.todayAmount?.toLocaleString() ?? '0'}`, color: 'var(--color-success)' },
    { label: t('trading_avg_discount'), value: `${statsData.avgDiscount ?? 0}%`, color: 'var(--color-info)' },
    { label: t('trading_large_trades'), value: String(statsData.largeTrades ?? 0), color: 'var(--color-warning)' },
  ] : [];

  const orders = ordersData?.items ?? [];

  return (
    <div>
      <h1 style={{ font: 'var(--text-h1)', marginBottom: 24 }}>{t('trading_title')}</h1>

      {/* Stats Row */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 24 }}>
        {statsLoading ? (
          <div style={{ ...loadingBox, gridColumn: '1 / -1' }}>Loading...</div>
        ) : tradingStats.map(s => (
          <div key={s.label} style={{
            background: 'var(--color-surface)',
            borderRadius: 'var(--radius-md)',
            border: '1px solid var(--color-border-light)',
            padding: 16,
          }}>
            <div style={{ font: 'var(--text-body-sm)', color: 'var(--color-text-tertiary)' }}>{s.label}</div>
            <div style={{ font: 'var(--text-h2)', color: s.color, marginTop: 4 }}>{s.value}</div>
          </div>
        ))}
      </div>

      {/* Chart Area */}
      <div style={{
        background: 'var(--color-surface)',
        borderRadius: 'var(--radius-md)',
        border: '1px solid var(--color-border-light)',
        padding: 20,
        marginBottom: 24,
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
          <span style={{ font: 'var(--text-h3)' }}>{t('trading_volume_trend')}</span>
          <div style={{ display: 'flex', gap: 8 }}>
            {['1H', '24H', '7D', '30D'].map(p => (
              <button key={p} style={{
                padding: '4px 10px',
                border: '1px solid var(--color-border)',
                borderRadius: 'var(--radius-full)',
                background: p === '24H' ? 'var(--color-primary)' : 'none',
                color: p === '24H' ? 'white' : 'var(--color-text-tertiary)',
                cursor: 'pointer',
                font: 'var(--text-caption)',
              }}>{p}</button>
            ))}
          </div>
        </div>
        <div style={{
          height: 260,
          background: 'var(--color-gray-50)',
          borderRadius: 'var(--radius-sm)',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          color: 'var(--color-text-tertiary)',
        }}>
          Recharts 双轴图 (交易量柱状 + 金额折线)
        </div>
      </div>

      {/* Orders Table */}
      <div style={{
        background: 'var(--color-surface)',
        borderRadius: 'var(--radius-md)',
        border: '1px solid var(--color-border-light)',
        overflow: 'hidden',
      }}>
        <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--color-border-light)', display: 'flex', justifyContent: 'space-between' }}>
          <span style={{ font: 'var(--text-h3)' }}>{t('trading_order_management')}</span>
          <input
            placeholder={t('trading_search_order')}
            style={{
              width: 240,
              height: 32,
              border: '1px solid var(--color-border)',
              borderRadius: 'var(--radius-sm)',
              padding: '0 12px',
              font: 'var(--text-body-sm)',
            }}
          />
        </div>
        {error ? (
          <div style={loadingBox}>Error: {error.message}</div>
        ) : ordersLoading ? (
          <div style={loadingBox}>Loading...</div>
        ) : (
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ background: 'var(--color-gray-50)' }}>
                {[t('trading_th_order_id'), t('trading_th_type'), t('trading_th_coupon_name'), t('trading_th_buyer'), t('trading_th_seller'), t('trading_th_amount'), t('trading_th_status'), t('trading_th_time')].map(h => (
                  <th key={h} style={{
                    font: 'var(--text-label-sm)',
                    color: 'var(--color-text-tertiary)',
                    padding: '10px 14px',
                    textAlign: 'left',
                  }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {orders.map((order, i) => (
                <tr key={order.orderId || i} style={{ borderBottom: '1px solid var(--color-border-light)' }}>
                  <td style={{ font: 'var(--text-body-sm)', fontFamily: 'var(--font-family-mono)', padding: '10px 14px', color: 'var(--color-text-tertiary)' }}>
                    {order.orderId}
                  </td>
                  <td style={{ font: 'var(--text-label-sm)', padding: '10px 14px' }}>
                    {order.type}
                  </td>
                  <td style={{ font: 'var(--text-body-sm)', padding: '10px 14px' }}>
                    {order.couponName}
                  </td>
                  <td style={{ font: 'var(--text-body-sm)', padding: '10px 14px' }}>{order.buyer}</td>
                  <td style={{ font: 'var(--text-body-sm)', padding: '10px 14px' }}>
                    {order.seller || '-'}
                  </td>
                  <td style={{
                    font: 'var(--text-label-sm)',
                    color: 'var(--color-primary)',
                    padding: '10px 14px',
                  }}>
                    ${order.amount?.toFixed(2)}
                  </td>
                  <td style={{ padding: '10px 14px' }}>
                    <span style={{
                      padding: '2px 8px',
                      borderRadius: 'var(--radius-full)',
                      background: order.status === 'completed' ? 'var(--color-success-light)' : 'var(--color-warning-light)',
                      color: order.status === 'completed' ? 'var(--color-success)' : 'var(--color-warning)',
                      font: 'var(--text-caption)',
                    }}>
                      {order.status === 'completed' ? t('trading_status_completed') : t('trading_status_dispute')}
                    </span>
                  </td>
                  <td style={{ font: 'var(--text-body-sm)', color: 'var(--color-text-tertiary)', padding: '10px 14px' }}>
                    {order.time}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
};
