/**
 * Ensemble Signal Card Component
 * Displays the combined ML signal from multiple strategies
 */

import React from 'react';
import {
  ArrowTrendingUpIcon,
  ArrowTrendingDownIcon,
  MinusIcon,
  ScaleIcon,
  BeakerIcon,
  ClockIcon,
} from '@heroicons/react/24/solid';

interface StrategySignal {
  action: string;
  score: number;
  weight: number;
}

interface EnsembleSignal {
  symbol: string;
  timeframe: string;
  action: 'BUY' | 'SELL' | 'HOLD';
  strength: 'strong' | 'moderate' | 'weak';
  confidence: number;
  net_score: number;
  strategy_signals: {
    amd: StrategySignal;
    ict: StrategySignal;
    range: StrategySignal;
    tpsl: StrategySignal;
  };
  entry?: number;
  stop_loss?: number;
  take_profit?: number;
  risk_reward?: number;
  reasoning: string[];
  timestamp: string;
}

interface EnsembleSignalCardProps {
  signal: EnsembleSignal;
  onExecuteTrade?: (direction: 'buy' | 'sell', signal: EnsembleSignal) => void;
  className?: string;
}

export const EnsembleSignalCard: React.FC<EnsembleSignalCardProps> = ({
  signal,
  onExecuteTrade,
  className = '',
}) => {
  const getActionIcon = () => {
    switch (signal.action) {
      case 'BUY':
        return <ArrowTrendingUpIcon className="w-8 h-8 text-green-400" />;
      case 'SELL':
        return <ArrowTrendingDownIcon className="w-8 h-8 text-red-400" />;
      default:
        return <MinusIcon className="w-8 h-8 text-gray-400" />;
    }
  };

  const getActionColor = () => {
    switch (signal.action) {
      case 'BUY':
        return 'bg-green-500/20 text-green-400 border-green-500/30';
      case 'SELL':
        return 'bg-red-500/20 text-red-400 border-red-500/30';
      default:
        return 'bg-gray-500/20 text-gray-400 border-gray-500/30';
    }
  };

  const getStrengthLabel = () => {
    switch (signal.strength) {
      case 'strong':
        return { text: 'Strong Signal', color: 'text-green-400' };
      case 'moderate':
        return { text: 'Moderate Signal', color: 'text-yellow-400' };
      default:
        return { text: 'Weak Signal', color: 'text-gray-400' };
    }
  };

  const strengthInfo = getStrengthLabel();

  const formatScore = (score: number) => {
    return score >= 0 ? `+${score.toFixed(2)}` : score.toFixed(2);
  };

  const getScoreBarColor = (action: string) => {
    if (action === 'BUY') return 'bg-green-500';
    if (action === 'SELL') return 'bg-red-500';
    return 'bg-gray-500';
  };

  const strategies = [
    { key: 'amd', name: 'AMD', ...signal.strategy_signals.amd },
    { key: 'ict', name: 'ICT/SMC', ...signal.strategy_signals.ict },
    { key: 'range', name: 'Range', ...signal.strategy_signals.range },
    { key: 'tpsl', name: 'TP/SL', ...signal.strategy_signals.tpsl },
  ];

  return (
    <div className={`bg-gray-900 border border-gray-800 rounded-xl p-5 ${className}`}>
      {/* Header */}
      <div className="flex items-start justify-between mb-4">
        <div>
          <div className="flex items-center gap-2">
            <BeakerIcon className="w-5 h-5 text-purple-400" />
            <h3 className="text-lg font-bold text-white">Ensemble Signal</h3>
          </div>
          <div className="flex items-center gap-2 mt-1">
            <span className="text-xl font-bold text-white">{signal.symbol}</span>
            <span className="text-xs px-2 py-1 bg-gray-800 rounded text-gray-400">
              {signal.timeframe}
            </span>
          </div>
        </div>

        {/* Action Badge */}
        <div className={`flex items-center gap-2 px-4 py-2 rounded-lg border ${getActionColor()}`}>
          {getActionIcon()}
          <div className="text-right">
            <p className="text-xl font-bold">{signal.action}</p>
            <p className={`text-xs ${strengthInfo.color}`}>{strengthInfo.text}</p>
          </div>
        </div>
      </div>

      {/* Net Score Meter */}
      <div className="mb-4 p-3 bg-gray-800/50 rounded-lg">
        <div className="flex items-center justify-between mb-2">
          <span className="text-sm text-gray-400 flex items-center gap-1">
            <ScaleIcon className="w-4 h-4" />
            Net Score
          </span>
          <span className={`text-lg font-bold ${
            signal.net_score > 0 ? 'text-green-400' :
            signal.net_score < 0 ? 'text-red-400' : 'text-gray-400'
          }`}>
            {formatScore(signal.net_score)}
          </span>
        </div>
        <div className="relative h-3 bg-gray-700 rounded-full overflow-hidden">
          <div className="absolute inset-y-0 left-1/2 w-0.5 bg-gray-500" />
          <div
            className={`absolute inset-y-0 ${
              signal.net_score >= 0 ? 'left-1/2' : 'right-1/2'
            } ${signal.net_score >= 0 ? 'bg-green-500' : 'bg-red-500'} rounded-full transition-all`}
            style={{
              width: `${Math.min(Math.abs(signal.net_score) * 50, 50)}%`,
            }}
          />
        </div>
        <div className="flex justify-between text-xs text-gray-500 mt-1">
          <span>-1.0 (Strong Sell)</span>
          <span>+1.0 (Strong Buy)</span>
        </div>
      </div>

      {/* Confidence */}
      <div className="mb-4">
        <div className="flex items-center justify-between mb-1">
          <span className="text-sm text-gray-400">Confidence</span>
          <span className="text-sm font-semibold text-white">
            {Math.round(signal.confidence * 100)}%
          </span>
        </div>
        <div className="h-2 bg-gray-700 rounded-full overflow-hidden">
          <div
            className={`h-full rounded-full transition-all ${
              signal.confidence >= 0.7 ? 'bg-green-500' :
              signal.confidence >= 0.5 ? 'bg-yellow-500' : 'bg-red-500'
            }`}
            style={{ width: `${signal.confidence * 100}%` }}
          />
        </div>
      </div>

      {/* Strategy Breakdown */}
      <div className="mb-4">
        <h4 className="text-sm font-semibold text-gray-400 mb-3">Strategy Contributions</h4>
        <div className="space-y-2">
          {strategies.map((strategy) => (
            <div key={strategy.key} className="flex items-center gap-2">
              <div className="w-16 text-xs text-gray-400">{strategy.name}</div>
              <div className="flex-1 flex items-center gap-2">
                <div className="flex-1 h-2 bg-gray-700 rounded-full overflow-hidden">
                  <div
                    className={`h-full rounded-full ${getScoreBarColor(strategy.action)}`}
                    style={{ width: `${Math.abs(strategy.score) * 100}%` }}
                  />
                </div>
                <div className="w-12 text-xs text-right">
                  <span className={
                    strategy.action === 'BUY' ? 'text-green-400' :
                    strategy.action === 'SELL' ? 'text-red-400' : 'text-gray-400'
                  }>
                    {strategy.action}
                  </span>
                </div>
                <div className="w-10 text-xs text-gray-500 text-right">
                  {Math.round(strategy.weight * 100)}%
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Trade Levels */}
      {signal.entry && (
        <div className="mb-4 grid grid-cols-3 gap-2">
          <div className="p-2 bg-blue-900/20 border border-blue-800/30 rounded-lg">
            <p className="text-xs text-blue-400">Entry</p>
            <p className="font-mono text-sm text-white">{signal.entry.toFixed(5)}</p>
          </div>
          {signal.stop_loss && (
            <div className="p-2 bg-red-900/20 border border-red-800/30 rounded-lg">
              <p className="text-xs text-red-400">Stop Loss</p>
              <p className="font-mono text-sm text-white">{signal.stop_loss.toFixed(5)}</p>
            </div>
          )}
          {signal.take_profit && (
            <div className="p-2 bg-green-900/20 border border-green-800/30 rounded-lg">
              <p className="text-xs text-green-400">Take Profit</p>
              <p className="font-mono text-sm text-white">{signal.take_profit.toFixed(5)}</p>
            </div>
          )}
        </div>
      )}

      {/* Risk/Reward */}
      {signal.risk_reward && (
        <div className="mb-4 text-center">
          <span className="text-sm text-gray-400">Risk:Reward</span>
          <span className="ml-2 font-bold text-white">1:{signal.risk_reward.toFixed(1)}</span>
        </div>
      )}

      {/* Reasoning */}
      {signal.reasoning.length > 0 && (
        <div className="mb-4">
          <h4 className="text-sm font-semibold text-gray-400 mb-2">Analysis Reasoning</h4>
          <ul className="space-y-1">
            {signal.reasoning.slice(0, 4).map((reason, idx) => (
              <li key={idx} className="flex items-start gap-2 text-xs text-gray-300">
                <span className="text-purple-400">•</span>
                {reason}
              </li>
            ))}
          </ul>
        </div>
      )}

      {/* Timestamp */}
      <div className="flex items-center justify-center gap-1 text-xs text-gray-500 mb-4">
        <ClockIcon className="w-3 h-3" />
        {new Date(signal.timestamp).toLocaleString()}
      </div>

      {/* Execute Button */}
      {onExecuteTrade && signal.action !== 'HOLD' && signal.confidence >= 0.5 && (
        <button
          onClick={() => onExecuteTrade(
            signal.action === 'BUY' ? 'buy' : 'sell',
            signal
          )}
          className={`w-full py-3 rounded-lg font-semibold transition-colors ${
            signal.action === 'BUY'
              ? 'bg-green-600 hover:bg-green-700 text-white'
              : 'bg-red-600 hover:bg-red-700 text-white'
          }`}
        >
          Execute {signal.action} - {Math.round(signal.confidence * 100)}% Confidence
        </button>
      )}
    </div>
  );
};

export default EnsembleSignalCard;
