import { useState, useEffect } from 'react';
import { ArrowLeft, TrendingUp, TrendingDown, Target, Clock, BarChart3, Activity, Zap } from 'lucide-react';
import { KLineChart } from './KLineChart';
import type { FuturesProduct, CycleAnalysis, TechnicalIndicators, TradingAdvice } from '@/types';
import { generateCycleAnalysis, generateTechnicalIndicators, generateTradingAdvice } from '@/data/mockData';

interface ProductDetailProps {
  product: FuturesProduct;
  onBack: () => void;
}

function PeriodButton({ 
  label, 
  isActive, 
  onClick 
}: { 
  label: string; 
  isActive: boolean; 
  onClick: () => void;
}) {
  return (
    <button
      onClick={onClick}
      className={`px-4 py-2 rounded-lg text-sm font-semibold transition-all duration-200 ${
        isActive
          ? 'bg-binance-yellow text-text-ink'
          : 'bg-surface-snow text-text-secondary hover:bg-border-light hover:text-text-ink'
      }`}
    >
      {label}
    </button>
  );
}

function IndicatorCard({ 
  title, 
  value, 
  status, 
  signal 
}: { 
  title: string; 
  value: string; 
  status: string; 
  signal?: 'positive' | 'negative' | 'neutral';
}) {
  const signalColors = {
    positive: 'text-semantic-green',
    negative: 'text-semantic-red',
    neutral: 'text-text-slate',
  };
  
  return (
    <div className="p-3 rounded-lg border border-border-light bg-surface-snow">
      <div className="text-xs text-text-slate mb-1">{title}</div>
      <div className={`text-sm font-semibold ${signal ? signalColors[signal] : 'text-text-ink'}`}>{value}</div>
      <div className="text-xs text-text-slate mt-1">{status}</div>
    </div>
  );
}

function KeyLevelRow({ 
  label, 
  value, 
  type 
}: { 
  label: string; 
  value: number; 
  type: 'resistance' | 'support';
}) {
  return (
    <div className="flex items-center justify-between py-2 border-b border-border-light/50 last:border-0">
      <span className="text-sm text-text-slate">{label}</span>
      <span className={`text-sm font-mono font-semibold ${type === 'resistance' ? 'text-semantic-red' : 'text-semantic-green'}`}>
        {value.toLocaleString()}
      </span>
    </div>
  );
}

export function ProductDetail({ product, onBack }: ProductDetailProps) {
  const [selectedPeriod, setSelectedPeriod] = useState<'m5' | 'm15' | 'm30' | 'm60'>('m15');
  const [cycleData, setCycleData] = useState<CycleAnalysis | null>(null);
  const [indicators, setIndicators] = useState<TechnicalIndicators | null>(null);
  const [advice, setAdvice] = useState<TradingAdvice | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    setLoading(true);
    setTimeout(() => {
      setCycleData(generateCycleAnalysis(product.id, selectedPeriod));
      setIndicators(generateTechnicalIndicators(product.id));
      setAdvice(generateTradingAdvice(product.id));
      setLoading(false);
    }, 300);
  }, [product.id, selectedPeriod]);

  const isUp = product.change >= 0;
  
  const periods = [
    { key: 'm5', label: '5分钟' },
    { key: 'm15', label: '15分钟' },
    { key: 'm30', label: '30分钟' },
    { key: 'm60', label: '60分钟' },
  ];

  const cycleLabels: Record<string, string> = {
    m5: '5分钟',
    m15: '15分钟',
    m30: '30分钟',
    m60: '60分钟',
  };

  return (
    <div className="space-y-space-4">
      <div className="flex items-center gap-4">
        <button
          onClick={onBack}
          className="flex items-center gap-2 px-4 py-2 rounded-lg border border-binanceBorder-light bg-white text-text-secondary hover:text-text-ink hover:border-binance-gold transition-colors"
        >
          <ArrowLeft className="w-4 h-4" />
          <span>返回</span>
        </button>
        <div>
          <h2 className="text-xl font-bold text-text-ink">{product.name} ({product.code})</h2>
          <p className="text-sm text-text-slate">详细技术分析</p>
        </div>
      </div>

      <div className="p-4 rounded-card border border-border-light bg-white">
        <div className="flex flex-wrap items-center gap-6">
          <div>
            <div className={`text-3xl font-bold font-mono ${isUp ? 'text-semantic-green' : 'text-semantic-red'}`}>
              ¥{product.price.toLocaleString()}
            </div>
            <div className={`flex items-center gap-1 text-sm ${isUp ? 'text-semantic-green' : 'text-semantic-red'}`}>
              {isUp ? <TrendingUp className="w-4 h-4" /> : <TrendingDown className="w-4 h-4" />}
              <span>{isUp ? '+' : ''}{product.change.toFixed(2)} ({isUp ? '+' : ''}{product.changePercent}%)</span>
            </div>
          </div>
          
          <div className="h-12 w-px bg-border-light hidden sm:block" />
          
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
            <div>
              <div className="text-xs text-text-slate">开盘</div>
              <div className="text-sm font-mono text-text-ink">{product.open.toLocaleString()}</div>
            </div>
            <div>
              <div className="text-xs text-text-slate">最高</div>
              <div className="text-sm font-mono text-semantic-green">{product.high.toLocaleString()}</div>
            </div>
            <div>
              <div className="text-xs text-text-slate">最低</div>
              <div className="text-sm font-mono text-semantic-red">{product.low.toLocaleString()}</div>
            </div>
            <div>
              <div className="text-xs text-text-slate">持仓量</div>
              <div className="text-sm font-mono text-text-ink">{product.openInterest.toLocaleString()}</div>
            </div>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-space-4">
        <div className="lg:col-span-2 space-y-space-4">
          <div className="flex items-center gap-2">
            <Clock className="w-4 h-4 text-binance-yellow" />
            <span className="text-sm text-text-slate">周期选择</span>
            <div className="flex gap-2 ml-2">
              {periods.map((p) => (
                <PeriodButton
                  key={p.key}
                  label={p.label}
                  isActive={selectedPeriod === p.key}
                  onClick={() => setSelectedPeriod(p.key as any)}
                />
              ))}
            </div>
          </div>

          <div className="p-4 rounded-card border border-border-light bg-white">
            {loading ? (
              <div className="h-[500px] flex items-center justify-center">
                <div className="flex items-center gap-2 text-binance-yellow">
                  <div className="w-5 h-5 border-2 border-binance-yellow border-t-transparent rounded-full animate-spin" />
                  <span>加载图表数据...</span>
                </div>
              </div>
            ) : cycleData ? (
              <KLineChart
                klineData={cycleData.klineData}
                macdData={cycleData.macdData}
                resistance={cycleData.keyLevels.resistance}
                support={cycleData.keyLevels.support}
                height={500}
              />
            ) : null}
          </div>
        </div>

        <div className="space-y-space-4">
          <div className="p-4 rounded-card border border-border-light bg-white">
            <div className="flex items-center gap-2 mb-space-4">
              <div className={`p-2 rounded-lg ${
                advice?.action === 'long' ? 'bg-semantic-green/10' : 
                advice?.action === 'short' ? 'bg-semantic-red/10' : 'bg-text-slate/10'
              }`}>
                <Target className={`w-4 h-4 ${
                  advice?.action === 'long' ? 'text-semantic-green' : 
                  advice?.action === 'short' ? 'text-semantic-red' : 'text-text-slate'
                }`} />
              </div>
              <h3 className="font-bold text-text-ink">交易建议</h3>
            </div>
            
            {advice && (
              <div className="space-y-3">
                <div className={`p-3 rounded-lg ${
                  advice.action === 'long' ? 'bg-semantic-green/10 border border-semantic-green/30' : 
                  advice.action === 'short' ? 'bg-semantic-red/10 border border-semantic-red/30' : 
                  'bg-text-slate/10 border border-text-slate/30'
                }`}>
                  <div className="text-xs text-text-slate mb-1">操作建议</div>
                  <div className={`text-lg font-bold ${
                    advice.action === 'long' ? 'text-semantic-green' : 
                    advice.action === 'short' ? 'text-semantic-red' : 'text-text-slate'
                  }`}>
                    {advice.action === 'long' ? '逢低做多' : advice.action === 'short' ? '逢高做空' : '观望等待'}
                  </div>
                  <div className="text-xs text-text-slate mt-1">{advice.reason}</div>
                </div>
                
                <div className="grid grid-cols-2 gap-2">
                  <div className="p-2 rounded-lg bg-surface-snow">
                    <div className="text-xs text-text-slate">建议入场</div>
                    <div className="text-sm font-mono text-text-ink">{advice.entryPrice.toLocaleString()}</div>
                  </div>
                  <div className="p-2 rounded-lg bg-surface-snow">
                    <div className="text-xs text-text-slate">目标价位</div>
                    <div className="text-sm font-mono text-semantic-green">{advice.targetPrice.toLocaleString()}</div>
                  </div>
                  <div className="p-2 rounded-lg bg-surface-snow">
                    <div className="text-xs text-text-slate">止损价位</div>
                    <div className="text-sm font-mono text-semantic-red">{advice.stopLoss.toLocaleString()}</div>
                  </div>
                  <div className="p-2 rounded-lg bg-surface-snow">
                    <div className="text-xs text-text-slate">风险等级</div>
                    <div className={`text-sm font-semibold ${
                      advice.riskLevel === 'low' ? 'text-semantic-green' : 
                      advice.riskLevel === 'medium' ? 'text-binance-gold' : 'text-semantic-red'
                    }`}>
                      {advice.riskLevel === 'low' ? '低' : advice.riskLevel === 'medium' ? '中' : '高'}
                    </div>
                  </div>
                </div>
              </div>
            )}
          </div>

          <div className="p-4 rounded-card border border-border-light bg-white">
            <div className="flex items-center gap-2 mb-space-4">
              <div className="p-2 rounded-lg bg-focus-blue/10">
                <Activity className="w-4 h-4 text-focus-blue" />
              </div>
              <h3 className="font-bold text-text-ink">技术指标</h3>
            </div>
            
            {indicators && (
              <div className="grid grid-cols-2 gap-2">
                <IndicatorCard
                  title="MACD"
                  value={indicators.macd.signal === 'golden_cross' ? '金叉' : indicators.macd.signal === 'dead_cross' ? '死叉' : '中性'}
                  status={`DIF: ${indicators.macd.value}`}
                  signal={indicators.macd.signal === 'golden_cross' ? 'positive' : indicators.macd.signal === 'dead_cross' ? 'negative' : 'neutral'}
                />
                <IndicatorCard
                  title="RSI"
                  value={`${indicators.rsi.value}`}
                  status={indicators.rsi.status === 'overbought' ? '超买' : indicators.rsi.status === 'oversold' ? '超卖' : '正常'}
                  signal={indicators.rsi.status === 'oversold' ? 'positive' : indicators.rsi.status === 'overbought' ? 'negative' : 'neutral'}
                />
                <IndicatorCard
                  title="布林带"
                  value={indicators.bollinger.position === 'upper' ? '上轨' : indicators.bollinger.position === 'lower' ? '下轨' : '中轨'}
                  status={`区间: ${indicators.bollinger.lower.toFixed(0)}-${indicators.bollinger.upper.toFixed(0)}`}
                  signal={indicators.bollinger.position === 'lower' ? 'positive' : indicators.bollinger.position === 'upper' ? 'negative' : 'neutral'}
                />
                <IndicatorCard
                  title="KDJ"
                  value={indicators.kdj.signal === 'golden_cross' ? '金叉' : indicators.kdj.signal === 'dead_cross' ? '死叉' : '中性'}
                  status={`K: ${indicators.kdj.k} D: ${indicators.kdj.d}`}
                  signal={indicators.kdj.signal === 'golden_cross' ? 'positive' : indicators.kdj.signal === 'dead_cross' ? 'negative' : 'neutral'}
                />
              </div>
            )}
          </div>

          <div className="p-4 rounded-card border border-border-light bg-white">
            <div className="flex items-center gap-2 mb-space-4">
              <div className="p-2 rounded-lg bg-binance-gold/10">
                <BarChart3 className="w-4 h-4 text-binance-gold" />
              </div>
              <h3 className="font-bold text-text-ink">关键点位</h3>
            </div>
            
            <div className="space-y-1">
              <div className="text-xs text-semantic-red font-semibold mb-2">压力位</div>
              {product.keyLevels.resistance.map((level, index) => (
                <KeyLevelRow key={index} label={`压力 ${index + 1}`} value={level} type="resistance" />
              ))}
            </div>
            
            <div className="mt-space-4 space-y-1">
              <div className="text-xs text-semantic-green font-semibold mb-2">支撑位</div>
              {product.keyLevels.support.map((level, index) => (
                <KeyLevelRow key={index} label={`支撑 ${index + 1}`} value={level} type="support" />
              ))}
            </div>
          </div>

          <div className="p-4 rounded-card border border-border-light bg-white">
            <div className="flex items-center gap-2 mb-space-4">
              <div className="p-2 rounded-lg bg-binance-yellow/10">
                <Zap className="w-4 h-4 text-binance-yellow" />
              </div>
              <h3 className="font-bold text-text-ink">多周期一致性</h3>
            </div>
            
            <div className="space-y-2">
              {Object.entries(product.cycles).map(([key, trend]) => (
                <div key={key} className="flex items-center justify-between py-1.5">
                  <span className="text-sm text-text-slate">{cycleLabels[key]}</span>
                  <div className={`flex items-center gap-1 px-2 py-1 rounded text-xs ${
                    trend === 'up' ? 'bg-semantic-green/10 text-semantic-green' : 
                    trend === 'down' ? 'bg-semantic-red/10 text-semantic-red' : 
                    'bg-text-slate/10 text-text-slate'
                  }`}>
                    {trend === 'up' ? <TrendingUp className="w-3 h-3" /> : trend === 'down' ? <TrendingDown className="w-3 h-3" /> : <div className="w-3 h-0.5 bg-current" />}
                    <span>{trend === 'up' ? '上涨' : trend === 'down' ? '下跌' : '震荡'}</span>
                  </div>
                </div>
              ))}
            </div>
            
            <div className="mt-space-4 pt-space-3 border-t border-binanceBorder-light">
              <div className="flex items-center justify-between">
                <span className="text-sm text-text-slate">周期共振度</span>
                <span className={`text-sm font-bold ${product.trendScore >= 80 ? 'text-semantic-green' : product.trendScore >= 60 ? 'text-binance-gold' : 'text-semantic-red'}`}>
                  {product.trendScore}%
                </span>
              </div>
              <div className="mt-2 h-2 bg-binanceBorder-light rounded-full overflow-hidden">
                <div
                  className={`h-full rounded-full transition-all duration-500 ${
                    product.trendScore >= 80 ? 'bg-semantic-green' : product.trendScore >= 60 ? 'bg-binance-gold' : 'bg-semantic-red'
                  }`}
                  style={{ width: `${product.trendScore}%` }}
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}