/**
 * SignalsTimeline Component
 * Displays a timeline of recent ML signals with their status
 */

import React from 'react';
import {
  ArrowTrendingUpIcon,
  ArrowTrendingDownIcon,
  CheckCircleIcon,
  XCircleIcon,
  ClockIcon,
} from '@heroicons/react/24/solid';
import type { MLSignal } from '../../../services/mlService';

interface SignalHistoryItem extends MLSignal {
  status?: 'pending' | 'success' | 'failed' | 'expired';
  outcome_pnl?: number;
}

interface SignalsTimelineProps {
  signals: SignalHistoryItem[];
  maxItems?: number;
  className?: string;
}

export const SignalsTimeline: React.FC<SignalsTimelineProps> = ({
  signals,
  maxItems = 10,
  className = '',
}) => {
  // Get status icon and color
  const getStatusConfig = (status?: string) => {
    switch (status) {
      case 'success':
        return {
          icon: CheckCircleIcon,
          color: 'text-green-400',
          bgColor: 'bg-green-500/20',
          label: 'Hit TP',
        };
      case 'failed':
        return {
          icon: XCircleIcon,
          color: 'text-red-400',
          bgColor: 'bg-red-500/20',
          label: 'Hit SL',
        };
      case 'expired':
        return {
          icon: ClockIcon,
          color: 'text-gray-400',
          bgColor: 'bg-gray-500/20',
          label: 'Expired',
        };
      default:
        return {
          icon: ClockIcon,
          color: 'text-yellow-400',
          bgColor: 'bg-yellow-500/20',
          label: 'Active',
        };
    }
  };

  // Format time ago
  const getTimeAgo = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / 60000);

    if (diffMins < 1) return 'Just now';
    if (diffMins < 60) return `${diffMins}m ago`;
    const diffHours = Math.floor(diffMins / 60);
    if (diffHours < 24) return `${diffHours}h ago`;
    const diffDays = Math.floor(diffHours / 24);
    return `${diffDays}d ago`;
  };

  const displayedSignals = signals.slice(0, maxItems);

  if (displayedSignals.length === 0) {
    return (
      <div className={`card p-6 ${className}`}>
        <h3 className="text-lg font-bold text-white mb-4">Recent Signals</h3>
        <div className="text-center py-8 text-gray-500">
          <ClockIcon className="w-12 h-12 mx-auto mb-3 opacity-50" />
          <p className="text-sm">No signals history available</p>
        </div>
      </div>
    );
  }

  return (
    <div className={`card p-6 ${className}`}>
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-lg font-bold text-white">Recent Signals</h3>
        <span className="text-xs text-gray-400">{signals.length} total</span>
      </div>

      <div className="space-y-3">
        {displayedSignals.map((signal, index) => {
          const statusConfig = getStatusConfig(signal.status);
          const StatusIcon = statusConfig.icon;
          const isLong = signal.direction === 'long';

          return (
            <div
              key={signal.signal_id || index}
              className="relative pl-6 pb-4 border-l-2 border-gray-700 last:border-l-0 last:pb-0"
            >
              {/* Timeline dot */}
              <div
                className={`absolute left-0 top-0 -translate-x-1/2 w-3 h-3 rounded-full ${
                  isLong ? 'bg-green-500' : 'bg-red-500'
                } ring-2 ring-gray-900`}
              />

              {/* Signal content */}
              <div className="bg-gray-800 rounded-lg p-3 hover:bg-gray-750 transition-colors">
                <div className="flex items-start justify-between mb-2">
                  <div className="flex items-center gap-2">
                    <div
                      className={`p-1 rounded ${
                        isLong ? 'bg-green-500/20' : 'bg-red-500/20'
                      }`}
                    >
                      {isLong ? (
                        <ArrowTrendingUpIcon className="w-3 h-3 text-green-400" />
                      ) : (
                        <ArrowTrendingDownIcon className="w-3 h-3 text-red-400" />
                      )}
                    </div>
                    <span className="font-bold text-white text-sm">{signal.symbol}</span>
                    <span
                      className={`text-xs px-2 py-0.5 rounded-full font-semibold ${
                        isLong ? 'bg-green-500/20 text-green-400' : 'bg-red-500/20 text-red-400'
                      }`}
                    >
                      {signal.direction.toUpperCase()}
                    </span>
                  </div>

                  {/* Status badge */}
                  <div className="flex items-center gap-1">
                    <StatusIcon className={`w-4 h-4 ${statusConfig.color}`} />
                    <span className={`text-xs ${statusConfig.color}`}>
                      {statusConfig.label}
                    </span>
                  </div>
                </div>

                {/* Price levels */}
                <div className="grid grid-cols-3 gap-1.5 text-xs mb-2">
                  <div>
                    <span className="text-gray-500">Entry:</span>
                    <span className="ml-1 text-gray-300 font-mono">
                      ${signal.entry_price.toFixed(2)}
                    </span>
                  </div>
                  <div>
                    <span className="text-gray-500">SL:</span>
                    <span className="ml-1 text-red-400 font-mono">
                      ${signal.stop_loss.toFixed(2)}
                    </span>
                  </div>
                  <div>
                    <span className="text-gray-500">TP:</span>
                    <span className="ml-1 text-green-400 font-mono">
                      ${signal.take_profit.toFixed(2)}
                    </span>
                  </div>
                </div>

                {/* Bottom row with metrics */}
                <div className="flex items-center justify-between text-xs">
                  <div className="flex items-center gap-3 text-gray-400">
                    <span>
                      Confidence: <span className="text-white">{Math.round(signal.confidence_score * 100)}%</span>
                    </span>
                    <span>
                      R:R: <span className="text-white">{signal.risk_reward_ratio.toFixed(1)}</span>
                    </span>
                  </div>
                  {signal.outcome_pnl !== undefined && (
                    <span
                      className={`font-bold ${
                        signal.outcome_pnl >= 0 ? 'text-green-400' : 'text-red-400'
                      }`}
                    >
                      {signal.outcome_pnl >= 0 ? '+' : ''}
                      {signal.outcome_pnl.toFixed(2)}%
                    </span>
                  )}
                  <span className="text-gray-500">{getTimeAgo(signal.created_at)}</span>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* View all link */}
      {signals.length > maxItems && (
        <div className="mt-4 text-center">
          <button className="text-sm text-blue-400 hover:text-blue-300 transition-colors">
            View all {signals.length} signals
          </button>
        </div>
      )}
    </div>
  );
};

export default SignalsTimeline;
