import { useMemo } from 'react';
import { TrendingUp, TrendingDown, AlertCircle, CheckCircle } from 'lucide-react';

/**
 * Trend Analysis using EMA alignment, MACD, and RSI confirmation
 * For swing trading - ensures strong directional bias before entry
 */

export interface TrendStrength {
  direction: 'BULLISH' | 'BEARISH' | 'NEUTRAL';
  strength: 'WEAK' | 'MODERATE' | 'STRONG' | 'VERY_STRONG';
  confidence: number; // 0-100%
  score: number; // 0-100
}

export interface TrendConfirmationProps {
  // Price and indicators
  ema8: number;
  ema21: number;
  ema55: number;
  ema200: number;
  macdLine: number;
  macdSignal: number;
  rsi: number;
  
  // Optional context
  timeframe?: string;
  onTrendUpdate?: (trend: TrendStrength) => void;
}

export default function TrendConfirmation({
  ema8,
  ema21,
  ema55,
  ema200,
  macdLine,
  macdSignal,
  rsi,
  timeframe = '4h',
  onTrendUpdate,
}: TrendConfirmationProps) {
  const trendAnalysis = useMemo(() => {
    const analysis: TrendStrength = {
      direction: 'NEUTRAL',
      strength: 'WEAK',
      confidence: 0,
      score: 0,
    };

    let bullishScore = 0;
    let bearishScore = 0;
    const maxScore = 100;

    // ===== EMA ALIGNMENT (40 points total) =====
    // Short-term trend: EMA8 > EMA21
    if (ema8 > ema21) {
      bullishScore += 10;
    } else if (ema8 < ema21) {
      bearishScore += 10;
    }

    // Medium-term trend: EMA21 > EMA55
    if (ema21 > ema55) {
      bullishScore += 15;
    } else if (ema21 < ema55) {
      bearishScore += 15;
    }

    // Long-term trend: EMA55 > EMA200 (most important for swing)
    if (ema55 > ema200) {
      bullishScore += 15;
    } else if (ema55 < ema200) {
      bearishScore += 15;
    }

    // ===== MACD CONFIRMATION (35 points total) =====
    // MACD line above signal line (bullish)
    if (macdLine > macdSignal) {
      bullishScore += 20;
    } else if (macdLine < macdSignal) {
      bearishScore += 20;
    }

    // MACD histogram distance (15 points)
    const macdDiff = Math.abs(macdLine - macdSignal);
    if (macdDiff > 0.5) {
      if (macdLine > macdSignal) {
        bullishScore += 15;
      } else {
        bearishScore += 15;
      }
    } else {
      // Weak crossover, neutral region
      bullishScore += 7;
      bearishScore += 7;
    }

    // ===== RSI CONFIRMATION (25 points total) =====
    // RSI > 50 (bullish bias)
    if (rsi > 60) {
      bullishScore += 15; // Strong bullish
    } else if (rsi > 50) {
      bullishScore += 10; // Mild bullish
    }

    // RSI < 50 (bearish bias)
    if (rsi < 40) {
      bearishScore += 15; // Strong bearish
    } else if (rsi < 50) {
      bearishScore += 10; // Mild bearish
    }

    // Avoid extremes for swing trading
    if (rsi > 80 || rsi < 20) {
      // Potential reversal zone - reduce confidence
      if (rsi > 80) bearishScore += 5;
      if (rsi < 20) bullishScore += 5;
    }

    // ===== DETERMINE DIRECTION AND STRENGTH =====
    const normalizedBullish = (bullishScore / maxScore) * 100;
    const normalizedBearish = (bearishScore / maxScore) * 100;

    if (normalizedBullish > normalizedBearish + 10) {
      analysis.direction = 'BULLISH';
      analysis.score = normalizedBullish;
      analysis.confidence = Math.min(normalizedBullish, 100);

      if (normalizedBullish > 80) {
        analysis.strength = 'VERY_STRONG';
      } else if (normalizedBullish > 65) {
        analysis.strength = 'STRONG';
      } else if (normalizedBullish > 50) {
        analysis.strength = 'MODERATE';
      } else {
        analysis.strength = 'WEAK';
      }
    } else if (normalizedBearish > normalizedBullish + 10) {
      analysis.direction = 'BEARISH';
      analysis.score = normalizedBearish;
      analysis.confidence = Math.min(normalizedBearish, 100);

      if (normalizedBearish > 80) {
        analysis.strength = 'VERY_STRONG';
      } else if (normalizedBearish > 65) {
        analysis.strength = 'STRONG';
      } else if (normalizedBearish > 50) {
        analysis.strength = 'MODERATE';
      } else {
        analysis.strength = 'WEAK';
      }
    } else {
      analysis.direction = 'NEUTRAL';
      analysis.strength = 'WEAK';
      analysis.confidence = 0;
      analysis.score = Math.max(normalizedBullish, normalizedBearish);
    }

    return analysis;
  }, [ema8, ema21, ema55, ema200, macdLine, macdSignal, rsi]);

  // Trigger callback on update
  if (onTrendUpdate) {
    onTrendUpdate(trendAnalysis);
  }

  // Color and icon based on trend
  const isBullish = trendAnalysis.direction === 'BULLISH';
  const isBearish = trendAnalysis.direction === 'BEARISH';
  const isNeutral = trendAnalysis.direction === 'NEUTRAL';

  const bgColor = isBullish ? 'bg-emerald-500/10' : isBearish ? 'bg-red-500/10' : 'bg-slate-700/30';
  const borderColor = isBullish ? 'border-emerald-500/40' : isBearish ? 'border-red-500/40' : 'border-slate-600';
  const textColor = isBullish ? 'text-emerald-300' : isBearish ? 'text-red-300' : 'text-slate-400';

  const strengthColors = {
    VERY_STRONG: isBullish ? 'text-emerald-500' : isBearish ? 'text-red-500' : 'text-slate-500',
    STRONG: isBullish ? 'text-emerald-400' : isBearish ? 'text-red-400' : 'text-slate-400',
    MODERATE: isBullish ? 'text-emerald-300' : isBearish ? 'text-red-300' : 'text-slate-400',
    WEAK: 'text-slate-500',
  };

  const getStrengthBar = () => {
    const width = Math.max(trendAnalysis.confidence, 15); // Minimum visual width
    return `${width}%`;
  };

  return (
    <div className={`rounded-lg border ${borderColor} ${bgColor} p-4 space-y-3`}>
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          {isBullish && <TrendingUp className="w-5 h-5 text-emerald-400" />}
          {isBearish && <TrendingDown className="w-5 h-5 text-red-400" />}
          {isNeutral && <AlertCircle className="w-5 h-5 text-slate-500" />}
          <h3 className={`font-semibold ${textColor}`}>Trend Confirmation</h3>
        </div>
        <span className="text-xs font-mono text-slate-500">{timeframe}</span>
      </div>

      {/* Trend Direction & Strength */}
      <div className="bg-slate-800/50 rounded px-3 py-2 flex items-center justify-between">
        <div>
          <p className={`font-bold text-lg ${textColor}`}>
            {trendAnalysis.direction}
          </p>
          <p className={`text-xs ${strengthColors[trendAnalysis.strength]}`}>
            {trendAnalysis.strength} ({trendAnalysis.confidence.toFixed(0)}% confidence)
          </p>
        </div>
        <CheckCircle className={`w-6 h-6 ${
          trendAnalysis.strength === 'VERY_STRONG' ? (isBullish ? 'text-emerald-500' : 'text-red-500') :
          trendAnalysis.strength === 'STRONG' ? (isBullish ? 'text-emerald-400' : 'text-red-400') :
          trendAnalysis.strength === 'MODERATE' ? 'text-amber-400' : 'text-slate-500'
        }`} />
      </div>

      {/* Confidence Bar */}
      <div className="space-y-1">
        <div className="flex justify-between items-center">
          <span className="text-xs text-slate-400">Trend Strength</span>
          <span className="text-xs font-mono text-slate-500">{trendAnalysis.score.toFixed(0)}/100</span>
        </div>
        <div className="h-2 bg-slate-700/50 rounded-full overflow-hidden">
          <div
            className={`h-full rounded-full transition-all duration-300 ${
              isBullish ? 'bg-emerald-500' : isBearish ? 'bg-red-500' : 'bg-slate-500'
            }`}
            style={{ width: getStrengthBar() }}
          />
        </div>
      </div>

      {/* EMA Alignment Details */}
      <div className="grid grid-cols-3 gap-2 text-xs">
        <div className="bg-slate-800/30 rounded px-2 py-1.5">
          <p className="text-slate-500 mb-0.5">Short Term</p>
          <p className={`font-mono font-semibold ${ema8 > ema21 ? 'text-emerald-400' : ema8 < ema21 ? 'text-red-400' : 'text-slate-400'}`}>
            EMA8 {ema8 > ema21 ? '↑' : ema8 < ema21 ? '↓' : '='}
          </p>
          <p className="text-slate-600 text-xs">{ema8.toFixed(2)}</p>
        </div>
        <div className="bg-slate-800/30 rounded px-2 py-1.5">
          <p className="text-slate-500 mb-0.5">Medium Term</p>
          <p className={`font-mono font-semibold ${ema21 > ema55 ? 'text-emerald-400' : ema21 < ema55 ? 'text-red-400' : 'text-slate-400'}`}>
            EMA21 {ema21 > ema55 ? '↑' : ema21 < ema55 ? '↓' : '='}
          </p>
          <p className="text-slate-600 text-xs">{ema21.toFixed(2)}</p>
        </div>
        <div className="bg-slate-800/30 rounded px-2 py-1.5">
          <p className="text-slate-500 mb-0.5">Long Term</p>
          <p className={`font-mono font-semibold ${ema55 > ema200 ? 'text-emerald-400' : ema55 < ema200 ? 'text-red-400' : 'text-slate-400'}`}>
            EMA55 {ema55 > ema200 ? '↑' : ema55 < ema200 ? '↓' : '='}
          </p>
          <p className="text-slate-600 text-xs">{ema55.toFixed(2)}</p>
        </div>
      </div>

      {/* MACD Status */}
      <div className="bg-slate-800/30 rounded px-3 py-2 flex items-center justify-between">
        <div className="text-xs">
          <p className="text-slate-500 mb-1">MACD Signal</p>
          <p className={`font-mono ${macdLine > macdSignal ? 'text-emerald-400' : macdLine < macdSignal ? 'text-red-400' : 'text-slate-400'}`}>
            {macdLine > macdSignal ? '✓ Bullish Alignment' : macdLine < macdSignal ? '✗ Bearish Alignment' : '— Neutral Alignment'}
          </p>
        </div>
        <span className="text-xs text-slate-600 font-mono">{Math.abs(macdLine - macdSignal).toFixed(4)}</span>
      </div>

      {/* RSI Status */}
      <div className="bg-slate-800/30 rounded px-3 py-2 flex items-center justify-between">
        <div className="text-xs">
          <p className="text-slate-500 mb-1">RSI Condition</p>
          <p className={`font-mono ${
            rsi > 60 ? 'text-emerald-400' :
            rsi > 50 ? 'text-emerald-300' :
            rsi < 40 ? 'text-red-400' :
            rsi < 50 ? 'text-red-300' :
            'text-slate-400'
          }`}>
            RSI {rsi.toFixed(1)} {
              rsi > 70 ? '(Overbought - Caution)' :
              rsi > 60 ? '(Bullish)' :
              rsi > 40 ? '(Neutral)' :
              rsi < 30 ? '(Oversold - Caution)' :
              '(Bearish)'
            }
          </p>
        </div>
        <span className="text-xs text-slate-600 font-mono">{rsi.toFixed(1)}%</span>
      </div>

      {/* Recommendation */}
      <div className={`text-xs rounded px-3 py-2 ${
        trendAnalysis.strength === 'VERY_STRONG' 
          ? isBullish 
            ? 'bg-emerald-500/15 text-emerald-200 border border-emerald-500/30'
            : 'bg-red-500/15 text-red-200 border border-red-500/30'
          : trendAnalysis.strength === 'STRONG'
          ? 'bg-amber-500/15 text-amber-200 border border-amber-500/30'
          : 'bg-slate-700/30 text-slate-300 border border-slate-600'
      }`}>
        {trendAnalysis.strength === 'VERY_STRONG' && (
          <p>
            <span className="font-semibold">✓ Strong Entry Signal:</span> Trend is {trendAnalysis.direction.toLowerCase()} with excellent confirmation. 
            All indicators aligned. Ideal for swing entry.
          </p>
        )}
        {trendAnalysis.strength === 'STRONG' && (
          <p>
            <span className="font-semibold">✓ Good Entry Signal:</span> Trend is {trendAnalysis.direction.toLowerCase()} with strong confirmation. 
            Ready for swing entry.
          </p>
        )}
        {trendAnalysis.strength === 'MODERATE' && (
          <p>
            <span className="font-semibold">⚠ Moderate Signal:</span> Trend is {trendAnalysis.direction.toLowerCase()} but confirmation mixed. 
            Wait for stronger alignment or reduce position size.
          </p>
        )}
        {trendAnalysis.strength === 'WEAK' && (
          <p>
            <span className="font-semibold">✗ Weak Signal:</span> Trend is unclear. Wait for clearer confirmation before entering.
          </p>
        )}
      </div>
    </div>
  );
}
