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-medium transition-all duration-200 ${
        isActive
          ? 'bg-[#7dd75a] text-[#09090b]'
          : 'bg-[#27272a] text-[#a1a1aa] hover:bg-[#3f3f46] hover:text-white'
      }`}
    >
      {label}
    </button>
  );
}

// 指标卡片
function IndicatorCard({ 
  title, 
  value, 
  status, 
  signal 
}: { 
  title: string; 
  value: string; 
  status: string; 
  signal?: 'positive' | 'negative' | 'neutral';
}) {
  const signalColors = {
    positive: 'text-[#7dd75a]',
    negative: 'text-[#ef4444]',
    neutral: 'text-[#a1a1aa]',
  };
  
  return (
    <div className="p-3 rounded-lg border border-[#27272a] bg-[#09090b]">
      <div className="text-xs text-[#71717a] mb-1">{title}</div>
      <div className={`text-sm font-medium ${signal ? signalColors[signal] : 'text-white'}`}>{value}</div>
      <div className="text-xs text-[#a1a1aa] 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-[#27272a]/50 last:border-0">
      <span className="text-sm text-[#a1a1aa]">{label}</span>
      <span className={`text-sm font-mono font-medium ${type === 'resistance' ? 'text-[#ef4444]' : 'text-[#7dd75a]'}`}>
        {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-lg border border-[#27272a] bg-[#0d0d10] text-[#a1a1aa] hover:text-white hover:border-[#3f3f46] transition-colors"
        >
          <ArrowLeft className="w-4 h-4" />
          <span>返回</span>
        </button>
        <div>
          <h2 className="text-xl font-bold text-white">{product.name} ({product.code})</h2>
          <p className="text-sm text-[#71717a]">详细技术分析</p>
        </div>
      </div>

      {/* 价格信息栏 */}
      <div className="p-4 rounded-xl border border-[#27272a] bg-[#0d0d10]">
        <div className="flex flex-wrap items-center gap-6">
          <div>
            <div className={`text-3xl font-bold font-mono ${isUp ? 'text-[#7dd75a]' : 'text-[#ef4444]'}`}>
              ¥{product.price.toLocaleString()}
            </div>
            <div className={`flex items-center gap-1 text-sm ${isUp ? 'text-[#7dd75a]' : 'text-[#ef4444]'}`}>
              {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-[#27272a] hidden sm:block" />
          
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
            <div>
              <div className="text-xs text-[#71717a]">开盘</div>
              <div className="text-sm font-mono text-white">{product.open.toLocaleString()}</div>
            </div>
            <div>
              <div className="text-xs text-[#71717a]">最高</div>
              <div className="text-sm font-mono text-[#7dd75a]">{product.high.toLocaleString()}</div>
            </div>
            <div>
              <div className="text-xs text-[#71717a]">最低</div>
              <div className="text-sm font-mono text-[#ef4444]">{product.low.toLocaleString()}</div>
            </div>
            <div>
              <div className="text-xs text-[#71717a]">持仓量</div>
              <div className="text-sm font-mono text-white">{product.openInterest.toLocaleString()}</div>
            </div>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
        {/* K线图区域 */}
        <div className="lg:col-span-2 space-y-4">
          {/* 周期切换 */}
          <div className="flex items-center gap-2">
            <Clock className="w-4 h-4 text-[#7dd75a]" />
            <span className="text-sm text-[#a1a1aa]">周期选择</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-xl border border-[#27272a] bg-[#0d0d10]">
            {loading ? (
              <div className="h-[500px] flex items-center justify-center">
                <div className="flex items-center gap-2 text-[#7dd75a]">
                  <div className="w-5 h-5 border-2 border-[#7dd75a] 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-xl border border-[#27272a] bg-[#0d0d10]">
            <div className="flex items-center gap-2 mb-4">
              <div className={`p-2 rounded-lg ${
                advice?.action === 'long' ? 'bg-[#7dd75a]/10' : 
                advice?.action === 'short' ? 'bg-[#ef4444]/10' : 'bg-[#a1a1aa]/10'
              }`}>
                <Target className={`w-4 h-4 ${
                  advice?.action === 'long' ? 'text-[#7dd75a]' : 
                  advice?.action === 'short' ? 'text-[#ef4444]' : 'text-[#a1a1aa]'
                }`} />
              </div>
              <h3 className="font-semibold text-white">交易建议</h3>
            </div>
            
            {advice && (
              <div className="space-y-3">
                <div className={`p-3 rounded-lg ${
                  advice.action === 'long' ? 'bg-[#7dd75a]/10 border border-[#7dd75a]/30' : 
                  advice.action === 'short' ? 'bg-[#ef4444]/10 border border-[#ef4444]/30' : 
                  'bg-[#a1a1aa]/10 border border-[#a1a1aa]/30'
                }`}>
                  <div className="text-xs text-[#71717a] mb-1">操作建议</div>
                  <div className={`text-lg font-bold ${
                    advice.action === 'long' ? 'text-[#7dd75a]' : 
                    advice.action === 'short' ? 'text-[#ef4444]' : 'text-[#a1a1aa]'
                  }`}>
                    {advice.action === 'long' ? '逢低做多' : advice.action === 'short' ? '逢高做空' : '观望等待'}
                  </div>
                  <div className="text-xs text-[#a1a1aa] mt-1">{advice.reason}</div>
                </div>
                
                <div className="grid grid-cols-2 gap-2">
                  <div className="p-2 rounded-lg bg-[#09090b]">
                    <div className="text-xs text-[#71717a]">建议入场</div>
                    <div className="text-sm font-mono text-white">{advice.entryPrice.toLocaleString()}</div>
                  </div>
                  <div className="p-2 rounded-lg bg-[#09090b]">
                    <div className="text-xs text-[#71717a]">目标价位</div>
                    <div className="text-sm font-mono text-[#7dd75a]">{advice.targetPrice.toLocaleString()}</div>
                  </div>
                  <div className="p-2 rounded-lg bg-[#09090b]">
                    <div className="text-xs text-[#71717a]">止损价位</div>
                    <div className="text-sm font-mono text-[#ef4444]">{advice.stopLoss.toLocaleString()}</div>
                  </div>
                  <div className="p-2 rounded-lg bg-[#09090b]">
                    <div className="text-xs text-[#71717a]">风险等级</div>
                    <div className={`text-sm font-medium ${
                      advice.riskLevel === 'low' ? 'text-[#7dd75a]' : 
                      advice.riskLevel === 'medium' ? 'text-[#f59e0b]' : 'text-[#ef4444]'
                    }`}>
                      {advice.riskLevel === 'low' ? '低' : advice.riskLevel === 'medium' ? '中' : '高'}
                    </div>
                  </div>
                </div>
              </div>
            )}
          </div>

          {/* 技术指标 */}
          <div className="p-4 rounded-xl border border-[#27272a] bg-[#0d0d10]">
            <div className="flex items-center gap-2 mb-4">
              <div className="p-2 rounded-lg bg-[#60a5fa]/10">
                <Activity className="w-4 h-4 text-[#60a5fa]" />
              </div>
              <h3 className="font-semibold text-white">技术指标</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-xl border border-[#27272a] bg-[#0d0d10]">
            <div className="flex items-center gap-2 mb-4">
              <div className="p-2 rounded-lg bg-[#f59e0b]/10">
                <BarChart3 className="w-4 h-4 text-[#f59e0b]" />
              </div>
              <h3 className="font-semibold text-white">关键点位</h3>
            </div>
            
            <div className="space-y-1">
              <div className="text-xs text-[#ef4444] 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-[#7dd75a] 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-xl border border-[#27272a] bg-[#0d0d10]">
            <div className="flex items-center gap-2 mb-4">
              <div className="p-2 rounded-lg bg-[#c084fc]/10">
                <Zap className="w-4 h-4 text-[#c084fc]" />
              </div>
              <h3 className="font-semibold text-white">多周期一致性</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-[#a1a1aa]">{cycleLabels[key]}</span>
                  <div className={`flex items-center gap-1 px-2 py-1 rounded text-xs ${
                    trend === 'up' ? 'bg-[#7dd75a]/10 text-[#7dd75a]' : 
                    trend === 'down' ? 'bg-[#ef4444]/10 text-[#ef4444]' : 
                    'bg-[#a1a1aa]/10 text-[#a1a1aa]'
                  }`}>
                    {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-[#27272a]">
              <div className="flex items-center justify-between">
                <span className="text-sm text-[#a1a1aa]">周期共振度</span>
                <span className={`text-sm font-bold ${product.trendScore >= 80 ? 'text-[#7dd75a]' : product.trendScore >= 60 ? 'text-[#f59e0b]' : 'text-[#ef4444]'}`}>
                  {product.trendScore}%
                </span>
              </div>
              <div className="mt-2 h-2 bg-[#27272a] rounded-full overflow-hidden">
                <div
                  className={`h-full rounded-full transition-all duration-500 ${
                    product.trendScore >= 80 ? 'bg-[#7dd75a]' : product.trendScore >= 60 ? 'bg-[#f59e0b]' : 'bg-[#ef4444]'
                  }`}
                  style={{ width: `${product.trendScore}%` }}
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
