/**
 * MLSignalsPanel Component
 * Displays ML-generated trading signals and predictions
 */

import React, { useEffect, useState, useCallback } from 'react';
import { Link } from 'react-router-dom';
import {
  ArrowTrendingUpIcon,
  ArrowTrendingDownIcon,
  SparklesIcon,
  ShieldCheckIcon,
  ClockIcon,
  ArrowPathIcon,
  ExclamationTriangleIcon,
  ChartBarIcon,
} from '@heroicons/react/24/solid';
import {
  getLatestSignal,
  getAMDPhase,
  getRangePrediction,
  generateSignal,
  type MLSignal,
  type AMDPhase,
  type RangePrediction,
} from '../../../services/mlService';

interface MLSignalsPanelProps {
  symbol: string;
  currentPrice?: number;
  onTradeSignal?: (signal: MLSignal) => void;
}

export const MLSignalsPanel: React.FC<MLSignalsPanelProps> = ({
  symbol,
  currentPrice,
  onTradeSignal,
}) => {
  const [signal, setSignal] = useState<MLSignal | null>(null);
  const [amdPhase, setAmdPhase] = useState<AMDPhase | null>(null);
  const [rangePrediction, setRangePrediction] = useState<RangePrediction | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [lastUpdate, setLastUpdate] = useState<Date | null>(null);

  // Fetch all ML data
  const fetchMLData = useCallback(async () => {
    setLoading(true);
    setError(null);

    try {
      const [signalData, amdData, rangeData] = await Promise.all([
        getLatestSignal(symbol),
        getAMDPhase(symbol),
        getRangePrediction(symbol, '1h'),
      ]);

      setSignal(signalData);
      setAmdPhase(amdData);
      setRangePrediction(rangeData);
      setLastUpdate(new Date());
    } catch (err) {
      setError('Failed to fetch ML data');
      console.error('ML data fetch error:', err);
    } finally {
      setLoading(false);
    }
  }, [symbol]);

  // Generate new signal
  const handleGenerateSignal = async () => {
    setLoading(true);
    setError(null);

    try {
      const newSignal = await generateSignal(symbol);
      if (newSignal) {
        setSignal(newSignal);
        setLastUpdate(new Date());
      }
    } catch (err) {
      setError('Failed to generate signal');
      console.error('Signal generation error:', err);
    } finally {
      setLoading(false);
    }
  };

  // Fetch data on mount and symbol change
  useEffect(() => {
    fetchMLData();

    // Refresh every 60 seconds
    const interval = setInterval(fetchMLData, 60000);
    return () => clearInterval(interval);
  }, [fetchMLData]);

  // Get AMD phase color
  const getPhaseColor = (phase: string) => {
    switch (phase?.toLowerCase()) {
      case 'accumulation':
        return 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300';
      case 'manipulation':
        return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-300';
      case 'distribution':
        return 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-300';
      default:
        return 'bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-300';
    }
  };

  // Get confidence color
  const getConfidenceColor = (confidence: number) => {
    if (confidence >= 0.7) return 'text-green-400';
    if (confidence >= 0.5) return 'text-yellow-400';
    return 'text-red-400';
  };

  return (
    <div className="space-y-4">
      {/* Header with refresh button and dashboard link */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <SparklesIcon className="w-5 h-5 text-blue-400" />
          <h3 className="text-lg font-semibold text-white">ML Signals</h3>
        </div>
        <div className="flex items-center gap-2">
          {lastUpdate && (
            <span className="text-xs text-gray-400">
              Updated {lastUpdate.toLocaleTimeString()}
            </span>
          )}
          <button
            onClick={fetchMLData}
            disabled={loading}
            className="p-1.5 text-gray-400 hover:text-white hover:bg-gray-700 rounded transition-colors disabled:opacity-50"
            title="Refresh signals"
          >
            <ArrowPathIcon className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
          </button>
        </div>
      </div>

      {/* Link to ML Dashboard */}
      <Link
        to="/ml-dashboard"
        className="flex items-center justify-center gap-2 p-3 bg-gradient-to-r from-blue-600/20 to-purple-600/20 border border-blue-500/30 rounded-lg hover:border-blue-500/50 transition-colors group"
      >
        <ChartBarIcon className="w-4 h-4 text-blue-400 group-hover:text-blue-300" />
        <span className="text-sm font-medium text-blue-400 group-hover:text-blue-300">
          Open Full ML Dashboard
        </span>
      </Link>

      {/* Error message */}
      {error && (
        <div className="flex items-center gap-2 p-3 bg-red-900/20 border border-red-800 rounded-lg">
          <ExclamationTriangleIcon className="w-5 h-5 text-red-400" />
          <span className="text-sm text-red-400">{error}</span>
        </div>
      )}

      {/* Active Signal */}
      <div className="card p-4">
        <div className="flex items-center justify-between mb-3">
          <h4 className="text-sm font-medium text-gray-400">Active Signal</h4>
          {!signal && (
            <button
              onClick={handleGenerateSignal}
              disabled={loading}
              className="text-xs px-2 py-1 bg-blue-600 hover:bg-blue-700 text-white rounded transition-colors disabled:opacity-50"
            >
              Generate
            </button>
          )}
        </div>

        {signal ? (
          <div className="space-y-3">
            {/* Direction and symbol */}
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <div
                  className={`p-2 rounded-lg ${
                    signal.direction === 'long'
                      ? 'bg-green-900/50'
                      : 'bg-red-900/50'
                  }`}
                >
                  {signal.direction === 'long' ? (
                    <ArrowTrendingUpIcon className="w-5 h-5 text-green-400" />
                  ) : (
                    <ArrowTrendingDownIcon className="w-5 h-5 text-red-400" />
                  )}
                </div>
                <div>
                  <span
                    className={`text-lg font-bold ${
                      signal.direction === 'long' ? 'text-green-400' : 'text-red-400'
                    }`}
                  >
                    {signal.direction.toUpperCase()}
                  </span>
                  <span className={`ml-2 text-xs px-2 py-0.5 rounded-full ${getPhaseColor(signal.amd_phase)}`}>
                    {signal.amd_phase}
                  </span>
                </div>
              </div>
              <span className={`text-lg font-bold ${getConfidenceColor(signal.confidence_score)}`}>
                {Math.round(signal.confidence_score * 100)}%
              </span>
            </div>

            {/* Price levels */}
            <div className="grid grid-cols-3 gap-2">
              <div className="text-center p-2 bg-gray-800 rounded">
                <p className="text-xs text-gray-400">Entry</p>
                <p className="font-mono font-bold text-white">
                  {signal.entry_price.toFixed(2)}
                </p>
              </div>
              <div className="text-center p-2 bg-red-900/30 rounded">
                <p className="text-xs text-red-400">Stop Loss</p>
                <p className="font-mono font-bold text-red-400">
                  {signal.stop_loss.toFixed(2)}
                </p>
              </div>
              <div className="text-center p-2 bg-green-900/30 rounded">
                <p className="text-xs text-green-400">Take Profit</p>
                <p className="font-mono font-bold text-green-400">
                  {signal.take_profit.toFixed(2)}
                </p>
              </div>
            </div>

            {/* Metrics */}
            <div className="grid grid-cols-2 gap-2 text-sm mb-3">
              <div className="flex items-center gap-1.5 text-gray-400 p-2 bg-gray-800 rounded">
                <ShieldCheckIcon className="w-4 h-4" />
                <div>
                  <p className="text-xs text-gray-500">Risk:Reward</p>
                  <p className="text-white font-bold">{signal.risk_reward_ratio.toFixed(1)}</p>
                </div>
              </div>
              <div className="flex items-center gap-1.5 text-gray-400 p-2 bg-gray-800 rounded">
                <ChartBarIcon className="w-4 h-4" />
                <div>
                  <p className="text-xs text-gray-500">P(TP First)</p>
                  <p className="text-white font-bold">{Math.round(signal.prob_tp_first * 100)}%</p>
                </div>
              </div>
            </div>

            {/* Valid Until */}
            <div className="flex items-center gap-2 p-2 bg-gray-800 rounded mb-3">
              <ClockIcon className="w-4 h-4 text-blue-400" />
              <div className="flex-1">
                <p className="text-xs text-gray-400">Valid Until</p>
                <p className="text-sm text-white font-medium">
                  {new Date(signal.valid_until).toLocaleString()}
                </p>
              </div>
            </div>

            {/* Trade button */}
            <button
              onClick={() => onTradeSignal?.(signal)}
              className={`w-full py-2 rounded-lg font-medium transition-colors ${
                signal.direction === 'long'
                  ? 'bg-green-600 hover:bg-green-700 text-white'
                  : 'bg-red-600 hover:bg-red-700 text-white'
              }`}
            >
              Execute Trade
            </button>
          </div>
        ) : (
          <div className="text-center py-6 text-gray-500">
            <SparklesIcon className="w-8 h-8 mx-auto mb-2 opacity-50" />
            <p className="text-sm">No active signal for {symbol}</p>
            <p className="text-xs mt-1">Click "Generate" to create a new signal</p>
          </div>
        )}
      </div>

      {/* AMD Phase */}
      {amdPhase && (
        <div className="card p-4">
          <h4 className="text-sm font-medium text-gray-400 mb-3">AMD Phase Detection</h4>
          <div className="flex items-center justify-between mb-3">
            <span className={`px-3 py-1 rounded-full text-sm font-medium ${getPhaseColor(amdPhase.phase)}`}>
              {amdPhase.phase.charAt(0).toUpperCase() + amdPhase.phase.slice(1)}
            </span>
            <span className={`font-bold ${getConfidenceColor(amdPhase.confidence)}`}>
              {Math.round(amdPhase.confidence * 100)}% confidence
            </span>
          </div>

          <div className="space-y-2 text-sm">
            <div className="flex justify-between">
              <span className="text-gray-400">Phase Duration</span>
              <span className="text-white">{amdPhase.phase_duration_bars} bars</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-400">Support</span>
              <span className="text-green-400 font-mono">{amdPhase.key_levels.support.toFixed(2)}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-400">Resistance</span>
              <span className="text-red-400 font-mono">{amdPhase.key_levels.resistance.toFixed(2)}</span>
            </div>
          </div>

          {/* Next phase probabilities */}
          <div className="mt-3 pt-3 border-t border-gray-700">
            <p className="text-xs text-gray-400 mb-2">Next Phase Probability</p>
            <div className="flex gap-2">
              {Object.entries(amdPhase.next_phase_probability).map(([phase, prob]) => (
                <div key={phase} className="flex-1 text-center">
                  <div className="h-1 bg-gray-700 rounded-full overflow-hidden mb-1">
                    <div
                      className={`h-full ${
                        phase === 'accumulation'
                          ? 'bg-green-500'
                          : phase === 'manipulation'
                          ? 'bg-yellow-500'
                          : 'bg-red-500'
                      }`}
                      style={{ width: `${prob * 100}%` }}
                    />
                  </div>
                  <span className="text-xs text-gray-400">
                    {phase.slice(0, 3).toUpperCase()} {Math.round(prob * 100)}%
                  </span>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {/* Range Prediction */}
      {rangePrediction && (
        <div className="card p-4">
          <h4 className="text-sm font-medium text-gray-400 mb-3">Range Prediction (1H)</h4>

          <div className="space-y-3">
            {/* Current price and predictions */}
            <div className="flex items-center justify-between">
              <span className="text-gray-400">Current</span>
              <span className="text-white font-mono font-bold">
                {currentPrice?.toFixed(2) || rangePrediction.current_price.toFixed(2)}
              </span>
            </div>

            {/* Predicted range visualization */}
            <div className="relative h-8 bg-gray-800 rounded-lg overflow-hidden">
              <div
                className="absolute inset-y-0 bg-gradient-to-r from-red-600/50 via-gray-600/50 to-green-600/50"
                style={{
                  left: '10%',
                  right: '10%',
                }}
              />
              {/* Current price marker */}
              <div
                className="absolute top-0 bottom-0 w-0.5 bg-white"
                style={{
                  left: '50%',
                }}
              />
            </div>

            <div className="flex justify-between text-sm">
              <div className="text-red-400">
                <span className="block text-xs text-gray-400">Low</span>
                <span className="font-mono">{rangePrediction.predicted_low.toFixed(2)}</span>
                <span className="text-xs ml-1">
                  (-{((rangePrediction.current_price - rangePrediction.predicted_low) / rangePrediction.current_price * 100).toFixed(1)}%)
                </span>
              </div>
              <div className="text-green-400 text-right">
                <span className="block text-xs text-gray-400">High</span>
                <span className="font-mono">{rangePrediction.predicted_high.toFixed(2)}</span>
                <span className="text-xs ml-1">
                  (+{((rangePrediction.predicted_high - rangePrediction.current_price) / rangePrediction.current_price * 100).toFixed(1)}%)
                </span>
              </div>
            </div>

            {/* Volatility and confidence */}
            <div className="flex justify-between text-sm pt-2 border-t border-gray-700">
              <div>
                <span className="text-gray-400">Volatility: </span>
                <span className={`font-medium ${
                  rangePrediction.volatility_regime === 'low' ? 'text-green-400' :
                  rangePrediction.volatility_regime === 'normal' ? 'text-blue-400' :
                  rangePrediction.volatility_regime === 'high' ? 'text-yellow-400' :
                  'text-red-400'
                }`}>
                  {rangePrediction.volatility_regime.toUpperCase()}
                </span>
              </div>
              <div>
                <span className="text-gray-400">Confidence: </span>
                <span className={getConfidenceColor(rangePrediction.prediction_confidence)}>
                  {Math.round(rangePrediction.prediction_confidence * 100)}%
                </span>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default MLSignalsPanel;
