import React, { useState, useEffect } from 'react';
import { TrendingDown, TrendingUp } from 'lucide-react';
import { api } from '../services/api';
import CollapsibleUserGuide from './CollapsibleUserGuide';
import './RecommendationsViewer.css';

function RecommendationsViewer() {
  const [recommendations, setRecommendations] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [directionFilter, setDirectionFilter] = useState('');
  const [showDetails, setShowDetails] = useState({});
  const [marketType, setMarketType] = useState('futures'); // 'futures' | 'spot'

  const loadRecommendations = async () => {
    try {
      setLoading(true);
      setError(null);
      if (marketType === 'spot') {
        const result = await api.getSpotRecommendations({ limit: 50 });
        const data = result.data || [];
        setRecommendations(data);
      } else {
        const params = { type: 'realtime', limit: 50, min_signal_strength: 5 };
        if (directionFilter) params.direction = directionFilter;
        const result = await api.getRecommendations(params);
        const data = result.data || [];
        setRecommendations(data);
      }
    } catch (err) {
      setError(err.message);
      console.error('加载推荐失败:', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadRecommendations();
  }, [marketType]);

  useEffect(() => {
    if (marketType !== 'futures') return;
    // 合约：每10秒静默更新价格（不触发loading状态）
    const interval = setInterval(async () => {
      try {
        const result = await api.getRecommendations({
          type: 'realtime',
          direction: directionFilter,
          limit: 50,
          min_signal_strength: 5
        });
        const newData = result.data || [];
        if (newData.length === 0) return;
        const newDataMap = new Map(newData.map(rec => [rec.symbol, rec]));
        setRecommendations(prev => {
          const prevKeys = new Set(prev.map(rec => rec.symbol || rec.id));
          const updated = prev.map(prevRec => {
            const key = prevRec.symbol || prevRec.id;
            return newDataMap.get(key) || prevRec;
          });
          const newItems = newData.filter(newRec => !prevKeys.has(newRec.symbol));
          const merged = [...updated, ...newItems];
          const uniqueMap = new Map();
          merged.forEach(rec => { uniqueMap.set(rec.symbol || rec.id, rec); });
          return Array.from(uniqueMap.values());
        });
      } catch (err) {
        console.debug('静默更新价格失败:', err);
      }
    }, 10000);
    return () => clearInterval(interval);
  }, [marketType, directionFilter]);

  // 现货：每 30 秒静默刷新列表
  useEffect(() => {
    if (marketType !== 'spot') return;
    const interval = setInterval(async () => {
      try {
        const result = await api.getSpotRecommendations({ limit: 50 });
        const data = result.data || [];
        if (data.length) setRecommendations(data);
      } catch (err) {
        console.debug('静默更新现货推荐失败:', err);
      }
    }, 30000);
    return () => clearInterval(interval);
  }, [marketType]);

  const toggleDetails = (key) => {
    setShowDetails(prev => ({
      ...prev,
      [key]: !prev[key]
    }));
  };

  const formatTime = (timeStr) => {
    if (!timeStr) return '-';
    try {
      // 统一按“北京时间”显示，但要先把输入解析成正确的时间点（epoch）
      // 注意：部分来源会给出不带时区的字符串（如 "2026-01-19T05:54:04" 或 "2026-01-19 05:54:04"）
      // 这类字符串在浏览器里会被当作“本地时间”解析，导致显示偏差。
      const raw = String(timeStr).trim();

      let date = null;

      // 1) 纯数字：兼容 seconds/ms
      if (/^\d+$/.test(raw)) {
        const n = Number(raw);
        const ms = raw.length >= 13 ? n : n * 1000;
        date = new Date(ms);
      } else {
        // 2) "YYYY-MM-DD HH:mm:ss" -> 当作 UTC（历史推荐里常见），再转北京时间显示
        if (/^\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}(\.\d+)?$/.test(raw)) {
          const isoUtc = raw.replace(' ', 'T') + 'Z';
          date = new Date(isoUtc);
        } else if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?$/.test(raw)) {
          // 3) ISO 但无时区 -> 当作 UTC
          date = new Date(raw + 'Z');
        } else {
          // 4) 其他格式（包含 Z / +08:00 / RFC1123 等）交给浏览器解析
          date = new Date(raw);
        }
      }

      if (!date || isNaN(date.getTime())) return timeStr;

      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        timeZone: 'Asia/Shanghai'  // 明确使用北京时间
      });
    } catch (e) {
      return timeStr;
    }
  };

  const formatTimeMs = (ms) => {
    if (!ms && ms !== 0) return '-';
    try {
      const date = new Date(Number(ms));
      if (isNaN(date.getTime())) return '-';
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        timeZone: 'Asia/Shanghai'
      });
    } catch (e) {
      return '-';
    }
  };

  const fmtPrice = (v) => {
    const n = Number(v || 0);
    if (!isFinite(n)) return '-';
    // 低价币用更多小数位，避免“挂单价=止损价”只是显示精度导致的误解
    if (Math.abs(n) >= 100) return n.toFixed(2);
    if (Math.abs(n) >= 1) return n.toFixed(4);
    if (Math.abs(n) >= 0.01) return n.toFixed(6);
    return n.toFixed(8);
  };

  const getEntryStatus = (rec) => {
    try {
      const entry = Number(rec?.suggested_limit_price ?? rec?.planned_entry_price);
      const cur = Number(rec?.current_price);
      if (!isFinite(entry) || !isFinite(cur) || !rec?.direction) return null;
      if (rec.direction === 'BUY') {
        return cur <= entry ? { text: '已到价', cls: 'hit' } : { text: '未到价', cls: 'wait' };
      }
      return cur >= entry ? { text: '已到价', cls: 'hit' } : { text: '未到价', cls: 'wait' };
    } catch (e) {
      return null;
    }
  };

  const getSignalStrengthColor = (strength) => {
    if (strength >= 8) return 'signal-strong';
    if (strength >= 6) return 'signal-medium';
    return 'signal-weak';
  };

  return (
    <div className="recommendations-viewer">
      <div className="viewer-header">
        <h1>交易推荐</h1>
        <div className="header-info">
          <span className="update-info">
            {marketType === 'spot' ? '现货推荐每30秒更新' : '合约每10秒自动更新'}
          </span>
          <button 
            className="btn-refresh" 
            onClick={loadRecommendations}
            disabled={loading}
          >
            {loading ? '刷新中...' : '手动刷新'}
          </button>
        </div>
      </div>

      <div className="market-type-tabs">
        <button
          type="button"
          className={`tab ${marketType === 'futures' ? 'active' : ''}`}
          onClick={() => setMarketType('futures')}
        >
          合约
        </button>
        <button
          type="button"
          className={`tab ${marketType === 'spot' ? 'active' : ''}`}
          onClick={() => setMarketType('spot')}
        >
          现货
        </button>
      </div>
      {marketType === 'spot' && (
        <p className="spot-hint">现货推荐（只做多），数据来自定时扫描，仅供参考。</p>
      )}

      {marketType === 'futures' && (
        <div className="filters">
          <select 
            value={directionFilter} 
            onChange={(e) => setDirectionFilter(e.target.value)}
            className="filter-select"
          >
            <option value="">全部方向</option>
            <option value="BUY">做多</option>
            <option value="SELL">做空</option>
          </select>
        </div>
      )}

      {error && (
        <div className="error-message">
          {error}
        </div>
      )}

      {loading ? (
        <div className="loading">加载中...</div>
      ) : recommendations.length === 0 ? (
        <div className="empty-state">
          <p>暂无推荐记录</p>
        </div>
      ) : (
        <div className="recommendations-list">
          {recommendations.map((rec) => {
            const key = rec.id || rec.symbol;
            return (
              <div key={key} className="recommendation-card">
                <div className="card-header">
                  <div className="card-title">
                    <span className="symbol">{rec.symbol}</span>
                    <span className={`direction ${rec.direction.toLowerCase()}`}>
                      {rec.direction === 'BUY' ? '做多' : '做空'}
                    </span>
                  </div>
                  <div className="card-meta">
                    <span className={`signal-strength ${getSignalStrengthColor(rec.signal_strength)}`}>
                      信号强度: {rec.signal_strength}/10
                    </span>
                    {rec.recommendation_time && (
                      <span className="time" title="北京时间">{formatTime(rec.recommendation_time)}（北京）</span>
                    )}
                  </div>
                </div>

                <div className="card-content">
                  {/* 推荐分类和风险等级标签 */}
                  {(rec.recommendation_category || rec.risk_level) && (
                    <div className="recommendation-tags">
                      {rec.recommendation_category && (
                        <span className={`category-tag category-${rec.recommendation_category?.replace(/[（\(\)）]/g, '').replace(/\s+/g, '-').toLowerCase() || 'default'}`}>
                          {rec.recommendation_category}
                        </span>
                      )}
                      {rec.risk_level && (
                        <span className={`risk-tag risk-${rec.risk_level?.replace(/\s+/g, '-').toLowerCase() || 'medium'}`}>
                          风险: {rec.risk_level}
                        </span>
                      )}
                    </div>
                  )}

                  <div className="price-info">
                    <div className="price-item">
                      <label>当前价格:</label>
                      <span>
                        {fmtPrice(rec.current_price)} USDT
                        {(rec.current_price_source === 'mark_price' || rec.price_updated) && (
                          <span
                            className="price-updated-badge"
                            title={
                              rec.current_price_source === 'mark_price'
                                ? `标记价（Binance premiumIndex） 更新时间: ${formatTimeMs(rec.current_price_time_ms)}`
                                : '价格已通过WebSocket实时更新'
                            }
                          >
                            🟢
                          </span>
                        )}
                      </span>
                    </div>
                    {(rec.current_price_source || rec.current_price_time_ms) && (
                      <div className="price-item price-meta">
                        <label>价格时间:</label>
                        <span>
                          {rec.current_price_source === 'mark_price' ? '标记价' : (rec.current_price_source || 'snapshot')}
                          {rec.current_price_time_ms ? ` · ${formatTimeMs(rec.current_price_time_ms)}` : ''}
                        </span>
                      </div>
                    )}
                    {rec.change_percent !== undefined && rec.change_percent !== null && (
                      <div className="price-item">
                        <label>24h涨跌:</label>
                        <span className={rec.change_percent >= 0 ? 'positive' : 'negative'}>
                          {rec.change_percent >= 0 ? '+' : ''}{parseFloat(rec.change_percent).toFixed(2)}%
                        </span>
                      </div>
                    )}
                  </div>

                  {/* 用户指南（人话版计划） */}
                  {rec.user_guide && (
                    <div className={`user-guide ${rec.direction === 'BUY' ? 'buy-bg' : 'sell-bg'}`}>
                      <div className="user-guide-head">
                        <strong>📋 操作计划</strong>
                        <div className="user-guide-prices">
                          <span className={`ug-direction-badge ${rec.direction === 'BUY' ? 'buy' : 'sell'}`} title={rec.direction === 'BUY' ? '做多' : '做空'}>
                            {rec.direction === 'BUY' ? (
                              <TrendingUp className="ug-direction-icon" aria-label="做多" size={18} />
                            ) : (
                              <TrendingDown className="ug-direction-icon" aria-label="做空" size={18} />
                            )}
                          </span>
                          <span className="ug-pill entry">
                            入场 {fmtPrice(rec.suggested_limit_price ?? rec.planned_entry_price)} USDT
                            {(() => {
                              const st = getEntryStatus(rec);
                              return st ? <span className={`ug-entry-status ${st.cls}`}>{st.text}</span> : null;
                            })()}
                          </span>
                          <span className="ug-pill stop">
                            止损 {fmtPrice(rec.suggested_stop_loss)} USDT
                          </span>
                          <span className="ug-pill tp1">
                            目标1 {fmtPrice(rec.suggested_take_profit_1)} USDT
                          </span>
                          <span className="ug-pill tp2">
                            目标2 {fmtPrice(rec.suggested_take_profit_2)} USDT
                          </span>
                        </div>
                      </div>
                      <CollapsibleUserGuide text={rec.user_guide} maxHeight={160} />
                    </div>
                  )}

                  {/* 预期持仓时间（如果存在） */}
                  {rec.expected_hold_time && (
                    <div className="expected-hold-time">
                      <strong>⏱️ 预期持仓时间:</strong>
                      <span>{rec.expected_hold_time}</span>
                    </div>
                  )}

                  {/* 最大持仓天数提醒 */}
                  {rec.max_hold_days && (
                    <div className="max-hold-warning">
                      <strong>⚠️ 退出提醒:</strong>
                      <span>若持仓超过{rec.max_hold_days}天仍未触及第一目标，建议平仓离场重新评估</span>
                    </div>
                  )}

                  <button 
                    className="btn-toggle-details"
                    onClick={() => toggleDetails(key)}
                  >
                    {showDetails[key] ? '隐藏' : '显示'}详细信息
                  </button>

                  {showDetails[key] && (
                    <div className="details-panel">
                      <div className="details-section">
                        <h4>交易提示</h4>
                        <div className="market-info">
                          <div className="info-item">
                            <label>提示:</label>
                            <span>{rec.trading_tutorial || '-'}</span>
                          </div>
                        </div>
                      </div>

                      <div className="details-section">
                        <h4>技术分析原因</h4>
                        <div className="market-info">
                          <div className="info-item">
                            <label>原因:</label>
                            <span>{rec.recommendation_reason || '-'}</span>
                          </div>
                        </div>
                      </div>

                      <div className="details-section">
                        <h4>建议参数</h4>
                        <div className="suggested-params">
                          <div className="param-item order-type">
                            <label>订单类型:</label>
                            <span className="order-type-badge limit">限价单</span>
                          </div>
                          {rec.suggested_limit_price && (
                            <div className="param-item limit-price highlight">
                              <label>建议挂单价:</label>
                              <span className="limit-price-value highlight-price">
                                {fmtPrice(rec.suggested_limit_price)} USDT
                                {rec.current_price && (
                                  <span className="price-diff">
                                    ({rec.direction === 'BUY' ? '低于' : '高于'}当前价
                                    {Math.abs(((rec.suggested_limit_price - rec.current_price) / rec.current_price) * 100).toFixed(2)}%)
                                  </span>
                                )}
                              </span>
                            </div>
                          )}
                          <div className="param-item">
                            <label>建议止损:</label>
                            <span>{fmtPrice(rec.suggested_stop_loss)}</span>
                          </div>
                          <div className="param-item">
                            <label>第一目标:</label>
                            <span>{fmtPrice(rec.suggested_take_profit_1)}</span>
                          </div>
                          <div className="param-item">
                            <label>第二目标:</label>
                            <span>{fmtPrice(rec.suggested_take_profit_2)}</span>
                          </div>
                          <div className="param-item">
                            <label>建议仓位:</label>
                            <span>{(parseFloat(rec.suggested_position_percent || 0) * 100).toFixed(2)}%</span>
                          </div>
                          <div className="param-item">
                            <label>建议杠杆:</label>
                            <span>{rec.suggested_leverage || 10}x</span>
                          </div>
                        </div>
                      </div>

                      <div className="details-section">
                        <h4>技术指标</h4>
                        <div className="indicators-grid">
                          {rec.rsi && (
                            <div className="indicator-item">
                              <label>RSI:</label>
                              <span>{parseFloat(rec.rsi).toFixed(2)}</span>
                            </div>
                          )}
                          {rec.macd_histogram !== null && rec.macd_histogram !== undefined && (
                            <div className="indicator-item">
                              <label>MACD:</label>
                              <span>{parseFloat(rec.macd_histogram).toFixed(6)}</span>
                            </div>
                          )}
                          {rec.ema20 && (
                            <div className="indicator-item">
                              <label>EMA20:</label>
                              <span>{parseFloat(rec.ema20).toFixed(4)}</span>
                            </div>
                          )}
                          {rec.ema50 && (
                            <div className="indicator-item">
                              <label>EMA50:</label>
                              <span>{parseFloat(rec.ema50).toFixed(4)}</span>
                            </div>
                          )}
                          {rec.atr && (
                            <div className="indicator-item">
                              <label>ATR:</label>
                              <span>{parseFloat(rec.atr).toFixed(4)}</span>
                            </div>
                          )}
                        </div>
                      </div>
                      
                      {rec.market_regime && (
                        <div className="details-section">
                          <h4>市场状态</h4>
                          <p>{rec.market_regime === 'trending' ? '趋势市场' : '震荡市场'}</p>
                        </div>
                      )}
                      
                      {rec.trend_4h && (
                        <div className="details-section">
                          <h4>4H趋势</h4>
                          <p>
                            {rec.trend_4h === 'up' ? '上涨' : 
                             rec.trend_4h === 'down' ? '下跌' : '中性'}
                          </p>
                        </div>
                      )}
                      
                      {rec.volume_24h && (
                        <div className="details-section">
                          <h4>24小时成交量</h4>
                          <p>{parseFloat(rec.volume_24h).toFixed(2)}</p>
                        </div>
                      )}
                      
                      {rec.volatility && (
                        <div className="details-section">
                          <h4>波动率</h4>
                          <p>{parseFloat(rec.volatility).toFixed(4)}</p>
                        </div>
                      )}
                    </div>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

export default RecommendationsViewer;
