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-pill text-sm font-medium transition-all duration-200 ${
        isActive
          ? 'bg-revolut-dark text-revolut-white'
          : 'bg-revolut-surface text-revolut-midSlate hover:bg-revolut-grayTone'
      }`}
    >
      {label}
    </button>
  );
}

function IndicatorCard({ 
  title, 
  value, 
  status, 
  signal 
}: { 
  title: string; 
  value: string; 
  status: string; 
  signal?: 'positive' | 'negative' | 'neutral';
}) {
  const signalColors = {
    positive: 'text-revolut-teal',
    negative: 'text-revolut-danger',
    neutral: 'text-revolut-midSlate',
  };
  
  return (
    <div className="p-3 rounded-standard border border-revolut-grayTone bg-revolut-white">
      <div className="text-xs text-revolut-coolGray mb-1">{title}</div>
      <div className={`text-sm font-medium ${signal ? signalColors[signal] : 'text-revolut-dark'}`}>{value}</div>
      <div className="text-xs text-revolut-midSlate 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-revolut-grayTone/50 last:border-0">
      <span className="text-sm text-revolut-midSlate">{label}</span>
      <span className={`text-sm font-mono font-medium ${type === 'resistance' ? 'text-revolut-danger' : 'text-revolut-teal'}`}>
        {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-4">
      <div className="flex items-center gap-4">
        <button
          onClick={onBack}
          className="flex items-center gap-2 px-4 py-2 rounded-pill border border-revolut-grayTone bg-revolut-white text-revolut-midSlate hover:text-revolut-dark hover:border-revolut-midSlate transition-colors"
        >
          <ArrowLeft className="w-4 h-4" />
          <span>返回</span>
        </button>
        <div>
          <h2 className="text-xl font-medium text-revolut-dark heading-display">{product.name} ({product.code})</h2>
          <p className="text-sm text-revolut-midSlate">详细技术分析</p>
        </div>
      </div>

      <div className="p-4 rounded-card border border-revolut-grayTone bg-revolut-white">
        <div className="flex flex-wrap items-center gap-6">
          <div>
            <div className={`text-3xl font-medium font-mono ${isUp ? 'text-revolut-teal' : 'text-revolut-danger'}`}>
              ¥{product.price.toLocaleString()}
            </div>
            <div className={`flex items-center gap-1 text-sm ${isUp ? 'text-revolut-teal' : 'text-revolut-danger'}`}>
              {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-revolut-grayTone hidden sm:block" />
          
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
            <div>
              <div className="text-xs text-revolut-coolGray">开盘</div>
              <div className="text-sm font-mono text-revolut-dark">{product.open.toLocaleString()}</div>
            </div>
            <div>
              <div className="text-xs text-revolut-coolGray">最高</div>
              <div className="text-sm font-mono text-revolut-teal">{product.high.toLocaleString()}</div>
            </div>
            <div>
              <div className="text-xs text-revolut-coolGray">最低</div>
              <div className="text-sm font-mono text-revolut-danger">{product.low.toLocaleString()}</div>
            </div>
            <div>
              <div className="text-xs text-revolut-coolGray">持仓量</div>
              <div className="text-sm font-mono text-revolut-dark">{product.openInterest.toLocaleString()}</div>
            </div>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
        <div className="lg:col-span-2 space-y-4">
          <div className="flex items-center gap-2">
            <Clock className="w-4 h-4 text-revolut-blue" />
            <span className="text-sm text-revolut-midSlate">周期选择</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-revolut-grayTone bg-revolut-white">
            {loading ? (
              <div className="h-[500px] flex items-center justify-center">
                <div className="flex items-center gap-2 text-revolut-blue">
                  <div className="w-5 h-5 border-2 border-revolut-blue 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-4">
          <div className="p-4 rounded-card border border-revolut-grayTone bg-revolut-white">
            <div className="flex items-center gap-2 mb-4">
              <div className={`p-2 rounded-standard ${
                advice?.action === 'long' ? 'bg-revolut-teal/10' : 
                advice?.action === 'short' ? 'bg-revolut-danger/10' : 'bg-revolut-midSlate/10'
              }`}>
                <Target className={`w-4 h-4 ${
                  advice?.action === 'long' ? 'text-revolut-teal' : 
                  advice?.action === 'short' ? 'text-revolut-danger' : 'text-revolut-midSlate'
                }`} />
              </div>
              <h3 className="font-medium text-revolut-dark">交易建议</h3>
            </div>
            
            {advice && (
              <div className="space-y-3">
                <div className={`p-3 rounded-standard ${
                  advice.action === 'long' ? 'bg-revolut-teal/10 border border-revolut-teal/30' : 
                  advice.action === 'short' ? 'bg-revolut-danger/10 border border-revolut-danger/30' : 
                  'bg-revolut-midSlate/10 border border-revolut-midSlate/30'
                }`}>
                  <div className="text-xs text-revolut-coolGray mb-1">操作建议</div>
                  <div className={`text-lg font-medium ${
                    advice.action === 'long' ? 'text-revolut-teal' : 
                    advice.action === 'short' ? 'text-revolut-danger' : 'text-revolut-midSlate'
                  }`}>
                    {advice.action === 'long' ? '逢低做多' : advice.action === 'short' ? '逢高做空' : '观望等待'}
                  </div>
                  <div className="text-xs text-revolut-midSlate mt-1">{advice.reason}</div>
                </div>
                
                <div className="grid grid-cols-2 gap-2">
                  <div className="p-2 rounded-standard bg-revolut-surface">
                    <div className="text-xs text-revolut-coolGray">建议入场</div>
                    <div className="text-sm font-mono text-revolut-dark">{advice.entryPrice.toLocaleString()}</div>
                  </div>
                  <div className="p-2 rounded-standard bg-revolut-surface">
                    <div className="text-xs text-revolut-coolGray">目标价位</div>
                    <div className="text-sm font-mono text-revolut-teal">{advice.targetPrice.toLocaleString()}</div>
                  </div>
                  <div className="p-2 rounded-standard bg-revolut-surface">
                    <div className="text-xs text-revolut-coolGray">止损价位</div>
                    <div className="text-sm font-mono text-revolut-danger">{advice.stopLoss.toLocaleString()}</div>
                  </div>
                  <div className="p-2 rounded-standard bg-revolut-surface">
                    <div className="text-xs text-revolut-coolGray">风险等级</div>
                    <div className={`text-sm font-medium ${
                      advice.riskLevel === 'low' ? 'text-revolut-teal' : 
                      advice.riskLevel === 'medium' ? 'text-revolut-warning' : 'text-revolut-danger'
                    }`}>
                      {advice.riskLevel === 'low' ? '低' : advice.riskLevel === 'medium' ? '中' : '高'}
                    </div>
                  </div>
                </div>
              </div>
            )}
          </div>

          <div className="p-4 rounded-card border border-revolut-grayTone bg-revolut-white">
            <div className="flex items-center gap-2 mb-4">
              <div className="p-2 rounded-standard bg-revolut-blue/10">
                <Activity className="w-4 h-4 text-revolut-blue" />
              </div>
              <h3 className="font-medium text-revolut-dark">技术指标</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-revolut-grayTone bg-revolut-white">
            <div className="flex items-center gap-2 mb-4">
              <div className="p-2 rounded-standard bg-revolut-warning/10">
                <BarChart3 className="w-4 h-4 text-revolut-warning" />
              </div>
              <h3 className="font-medium text-revolut-dark">关键点位</h3>
            </div>
            
            <div className="space-y-1">
              <div className="text-xs text-revolut-danger font-medium mb-2">压力位</div>
              {product.keyLevels.resistance.map((level, index) => (
                <KeyLevelRow key={index} label={`压力 ${index + 1}`} value={level} type="resistance" />
              ))}
            </div>
            
            <div className="mt-4 space-y-1">
              <div className="text-xs text-revolut-teal font-medium 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-revolut-grayTone bg-revolut-white">
            <div className="flex items-center gap-2 mb-4">
              <div className="p-2 rounded-standard bg-revolut-deepPink/10">
                <Zap className="w-4 h-4 text-revolut-deepPink" />
              </div>
              <h3 className="font-medium text-revolut-dark">多周期一致性</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-revolut-midSlate">{cycleLabels[key]}</span>
                  <div className={`flex items-center gap-1 px-2 py-1 rounded-pill text-xs ${
                    trend === 'up' ? 'bg-revolut-teal/10 text-revolut-teal' : 
                    trend === 'down' ? 'bg-revolut-danger/10 text-revolut-danger' : 
                    'bg-revolut-midSlate/10 text-revolut-midSlate'
                  }`}>
                    {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-4 pt-3 border-t border-revolut-grayTone">
              <div className="flex items-center justify-between">
                <span className="text-sm text-revolut-midSlate">周期共振度</span>
                <span className={`text-sm font-medium ${product.trendScore >= 80 ? 'text-revolut-teal' : product.trendScore >= 60 ? 'text-revolut-warning' : 'text-revolut-danger'}`}>
                  {product.trendScore}%
                </span>
              </div>
              <div className="mt-2 h-2 bg-revolut-surface rounded-full overflow-hidden">
                <div
                  className={`h-full rounded-full transition-all duration-500 ${
                    product.trendScore >= 80 ? 'bg-revolut-teal' : product.trendScore >= 60 ? 'bg-revolut-warning' : 'bg-revolut-danger'
                  }`}
                  style={{ width: `${product.trendScore}%` }}
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}