import { useMemo, useState } from 'react';
import { AlertTriangle, TrendingUp, TrendingDown, Clock, X } from 'lucide-react';

/**
 * News Event Tracker for swing trading
 * Alerts on important economic events, earnings, and market-moving news
 * Helps avoid bad entry/exit times and position yourself before major moves
 */

export type EventImpact = 'HIGH' | 'MEDIUM' | 'LOW';
export type EventCategory = 'ECONOMIC' | 'EARNINGS' | 'FED' | 'GEOPOLITICAL' | 'SUPPLY_DEMAND';

export interface NewsEvent {
  id: string;
  title: string;
  category: EventCategory;
  impact: EventImpact;
  scheduledTime: string; // ISO datetime
  status: 'UPCOMING' | 'IN_PROGRESS' | 'COMPLETED';
  forecast?: number;
  actual?: number;
  previous?: number;
  sentiment?: 'BULLISH' | 'BEARISH' | 'NEUTRAL'; // For sentiment analysis
  description?: string;
  recommendation?: string; // Action for trader
}

export interface NewsEventTrackerProps {
  events: NewsEvent[];
  currentTime?: string; // ISO datetime (defaults to now)
  onEventAlert?: (event: NewsEvent) => void;
  showCompleted?: boolean;
}

export default function NewsEventTracker({
  events,
  currentTime = new Date().toISOString(),
  onEventAlert,
  showCompleted = false,
}: NewsEventTrackerProps) {
  const [dismissedIds, setDismissedIds] = useState<Set<string>>(new Set());
  const [expandedId, setExpandedId] = useState<string | null>(null);

  // Calculate time until event
  const getTimeUntil = (scheduledTime: string) => {
    const now = new Date(currentTime);
    const eventTime = new Date(scheduledTime);
    const diffMs = eventTime.getTime() - now.getTime();
    const diffMins = Math.round(diffMs / 60000);

    if (diffMins < 0) {
      const pastMins = Math.abs(diffMins);
      if (pastMins < 60) return `${pastMins}m ago`;
      const pastHours = Math.round(pastMins / 60);
      if (pastHours < 24) return `${pastHours}h ago`;
      const pastDays = Math.round(pastHours / 24);
      return `${pastDays}d ago`;
    }

    if (diffMins === 0) return 'Now';
    if (diffMins < 60) return `${diffMins}m`;
    const hours = Math.round(diffMins / 60);
    if (hours < 24) return `${hours}h`;
    const days = Math.round(hours / 24);
    return `${days}d`;
  };

  // Update event status based on time
  const getEventStatus = (event: NewsEvent) => {
    const now = new Date(currentTime);
    const eventTime = new Date(event.scheduledTime);
    const diffMs = eventTime.getTime() - now.getTime();

    if (diffMs < 0 && Math.abs(diffMs) > 3600000) {
      return 'COMPLETED';
    } else if (diffMs < 0 && diffMs > -3600000) {
      return 'IN_PROGRESS';
    } else {
      return 'UPCOMING';
    }
  };

  // Filter and sort events
  const filteredEvents = useMemo(() => {
    return events
      .filter(e => !dismissedIds.has(e.id))
      .filter(e => showCompleted || getEventStatus(e) !== 'COMPLETED')
      .sort((a, b) => {
        const aTime = new Date(a.scheduledTime).getTime();
        const bTime = new Date(b.scheduledTime).getTime();
        return aTime - bTime;
      });
  }, [events, dismissedIds, showCompleted, currentTime]);

  // Upcoming high-impact events
  const upcomingHighImpact = useMemo(() => {
    return filteredEvents.filter(
      e => getEventStatus(e) === 'UPCOMING' && e.impact === 'HIGH'
    );
  }, [filteredEvents]);

  const handleDismiss = (id: string) => {
    setDismissedIds(prev => new Set(prev).add(id));
  };

  const getCategoryIcon = (category: EventCategory) => {
    const iconClass = 'w-4 h-4';
    switch (category) {
      case 'ECONOMIC':
        return <TrendingUp className={`${iconClass} text-blue-400`} />;
      case 'EARNINGS':
        return <TrendingDown className={`${iconClass} text-purple-400`} />;
      case 'FED':
        return <AlertTriangle className={`${iconClass} text-red-400`} />;
      case 'GEOPOLITICAL':
        return <AlertTriangle className={`${iconClass} text-orange-400`} />;
      case 'SUPPLY_DEMAND':
        return <TrendingUp className={`${iconClass} text-amber-400`} />;
      default:
        return <Clock className={`${iconClass} text-slate-400`} />;
    }
  };

  const getImpactColor = (impact: EventImpact) => {
    switch (impact) {
      case 'HIGH':
        return 'bg-red-500/15 border-red-500/30 text-red-200';
      case 'MEDIUM':
        return 'bg-amber-500/15 border-amber-500/30 text-amber-200';
      case 'LOW':
        return 'bg-blue-500/15 border-blue-500/30 text-blue-200';
    }
  };

  const getSentimentColor = (sentiment?: string) => {
    switch (sentiment) {
      case 'BULLISH':
        return 'text-emerald-400';
      case 'BEARISH':
        return 'text-red-400';
      default:
        return 'text-slate-400';
    }
  };

  // Alert for upcoming high-impact events
  if (upcomingHighImpact.length > 0 && onEventAlert) {
    upcomingHighImpact.forEach(e => {
      const timeUntil = getTimeUntil(e.scheduledTime);
      if (timeUntil === '1h' || timeUntil === '5m' || timeUntil === '15m') {
        onEventAlert(e);
      }
    });
  }

  return (
    <div className="rounded-lg border border-slate-700 bg-slate-900 overflow-hidden">
      {/* Header */}
      <div className="bg-slate-800/50 p-4 border-b border-slate-700">
        <div className="flex items-center gap-2 mb-2">
          <AlertTriangle className="w-5 h-5 text-amber-500" />
          <h3 className="font-semibold text-slate-200">News Event Monitor</h3>
          {upcomingHighImpact.length > 0 && (
            <span className="ml-auto bg-red-500/20 text-red-300 text-xs px-2 py-1 rounded-full font-semibold">
              {upcomingHighImpact.length} High Impact Soon
            </span>
          )}
        </div>
        <p className="text-xs text-slate-500">
          {filteredEvents.length} events tracked • Avoid trading during high-impact events
        </p>
      </div>

      {/* Events List */}
      {filteredEvents.length === 0 ? (
        <div className="p-8 text-center text-slate-400">
          <Clock className="w-8 h-8 mx-auto mb-2 text-slate-600" />
          <p>No upcoming news events</p>
        </div>
      ) : (
        <div className="divide-y divide-slate-700/50">
          {filteredEvents.map(event => {
            const isExpanded = expandedId === event.id;
            const timeUntil = getTimeUntil(event.scheduledTime);
            const status = getEventStatus(event);
            const eventDate = new Date(event.scheduledTime);
            const formattedTime = eventDate.toLocaleTimeString('en-US', {
              hour: '2-digit',
              minute: '2-digit',
              hour12: true,
            });

            return (
              <div
                key={event.id}
                className={`p-3 transition-colors cursor-pointer hover:bg-slate-800/30 ${
                  isExpanded ? 'bg-slate-800/40' : ''
                }`}
                onClick={() => setExpandedId(isExpanded ? null : event.id)}
              >
                {/* Main Row */}
                <div className="flex items-start gap-3 justify-between mb-2">
                  {/* Left: Category and Title */}
                  <div className="flex items-start gap-3 flex-1 min-w-0">
                    <div className="mt-1">{getCategoryIcon(event.category)}</div>
                    <div className="min-w-0 flex-1">
                      <p className="text-sm font-semibold text-slate-200 truncate">
                        {event.title}
                      </p>
                      <div className="flex items-center gap-2 mt-1 flex-wrap">
                        <span className={`text-xs px-2 py-0.5 rounded border ${getImpactColor(event.impact)}`}>
                          {event.impact} Impact
                        </span>
                        <span className={`text-xs px-2 py-0.5 rounded ${
                          status === 'UPCOMING' ? 'bg-blue-500/20 text-blue-300' :
                          status === 'IN_PROGRESS' ? 'bg-orange-500/20 text-orange-300' :
                          'bg-slate-700/30 text-slate-400'
                        }`}>
                          {status === 'UPCOMING' ? `${timeUntil}` : status === 'IN_PROGRESS' ? 'In Progress' : 'Completed'}
                        </span>
                      </div>
                    </div>
                  </div>

                  {/* Right: Time & Action */}
                  <div className="text-right flex items-start gap-2">
                    <div className="text-xs text-slate-500">
                      <p className="font-mono">{formattedTime}</p>
                      <p className="text-slate-600">{eventDate.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}</p>
                    </div>
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        handleDismiss(event.id);
                      }}
                      className="p-1 hover:bg-slate-700/50 rounded transition-colors"
                      title="Dismiss"
                    >
                      <X className="w-4 h-4 text-slate-500 hover:text-slate-300" />
                    </button>
                  </div>
                </div>

                {/* Expanded Details */}
                {isExpanded && (
                  <div className="mt-3 pt-3 border-t border-slate-700/30 space-y-2">
                    {/* Category and Sentiment */}
                    <div className="grid grid-cols-2 gap-2 text-xs">
                      <div className="bg-slate-800/40 rounded px-2 py-1.5">
                        <p className="text-slate-500 mb-0.5">Category</p>
                        <p className="text-slate-300 font-semibold capitalize">
                          {event.category.replace(/_/g, ' ')}
                        </p>
                      </div>
                      {event.sentiment && (
                        <div className="bg-slate-800/40 rounded px-2 py-1.5">
                          <p className="text-slate-500 mb-0.5">Sentiment</p>
                          <p className={`font-semibold capitalize ${getSentimentColor(event.sentiment)}`}>
                            {event.sentiment}
                          </p>
                        </div>
                      )}
                    </div>

                    {/* Forecast vs Actual */}
                    {(event.forecast !== undefined || event.actual !== undefined || event.previous !== undefined) && (
                      <div className="bg-slate-800/40 rounded px-2 py-1.5 text-xs">
                        <p className="text-slate-500 mb-1">Data</p>
                        <div className="grid grid-cols-3 gap-2 font-mono text-slate-300">
                          {event.forecast !== undefined && (
                            <div>
                              <p className="text-slate-600 text-xs mb-0.5">Forecast</p>
                              <p className="font-semibold">{event.forecast}</p>
                            </div>
                          )}
                          {event.actual !== undefined && (
                            <div>
                              <p className="text-slate-600 text-xs mb-0.5">Actual</p>
                              <p className={`font-semibold ${
                                (event.forecast !== undefined && event.actual > event.forecast) 
                                  ? 'text-emerald-400'
                                  : event.forecast !== undefined && event.actual < event.forecast
                                  ? 'text-red-400'
                                  : 'text-slate-300'
                              }`}>
                                {event.actual}
                              </p>
                            </div>
                          )}
                          {event.previous !== undefined && (
                            <div>
                              <p className="text-slate-600 text-xs mb-0.5">Previous</p>
                              <p className="font-semibold">{event.previous}</p>
                            </div>
                          )}
                        </div>
                      </div>
                    )}

                    {/* Description */}
                    {event.description && (
                      <div className="bg-slate-800/40 rounded px-2 py-1.5 text-xs">
                        <p className="text-slate-500 mb-1">Details</p>
                        <p className="text-slate-300">{event.description}</p>
                      </div>
                    )}

                    {/* Recommendation */}
                    {event.recommendation && (
                      <div className={`rounded px-2 py-1.5 text-xs border ${
                        event.impact === 'HIGH'
                          ? 'bg-red-500/10 border-red-500/30 text-red-200'
                          : 'bg-amber-500/10 border-amber-500/30 text-amber-200'
                      }`}>
                        <p className="font-semibold mb-1">Recommendation:</p>
                        <p>{event.recommendation}</p>
                      </div>
                    )}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}

      {/* Footer: Event Count */}
      {filteredEvents.length > 0 && (
        <div className="px-4 py-2 bg-slate-800/30 border-t border-slate-700/50 text-xs text-slate-500">
          {filteredEvents.filter(e => getEventStatus(e) === 'UPCOMING').length} upcoming •{' '}
          {filteredEvents.filter(e => getEventStatus(e) === 'COMPLETED').length} completed
        </div>
      )}
    </div>
  );
}
