/**
 * TradeAlertsNotificationCenter Component
 * Unified notification hub for MT4-specific trading events
 */

import React, { useState, useEffect, useMemo } from 'react';
import {
  Bell,
  BellOff,
  X,
  Check,
  AlertTriangle,
  TrendingUp,
  TrendingDown,
  Target,
  Shield,
  Wifi,
  WifiOff,
  Volume2,
  VolumeX,
  Trash2,
  Filter,
  Clock,
  DollarSign,
} from 'lucide-react';

export type AlertType =
  | 'trade_opened'
  | 'trade_closed'
  | 'sl_hit'
  | 'tp_hit'
  | 'margin_warning'
  | 'margin_call'
  | 'price_alert'
  | 'connection_lost'
  | 'connection_restored'
  | 'order_filled'
  | 'order_rejected';

export type AlertPriority = 'low' | 'medium' | 'high' | 'critical';

export interface TradeAlert {
  id: string;
  type: AlertType;
  priority: AlertPriority;
  title: string;
  message: string;
  symbol?: string;
  ticket?: number;
  profit?: number;
  timestamp: string;
  read: boolean;
}

interface TradeAlertsNotificationCenterProps {
  alerts?: TradeAlert[];
  onMarkRead?: (alertId: string) => void;
  onMarkAllRead?: () => void;
  onDelete?: (alertId: string) => void;
  onClearAll?: () => void;
  soundEnabled?: boolean;
  onSoundToggle?: (enabled: boolean) => void;
  maxVisible?: number;
  compact?: boolean;
}

const TradeAlertsNotificationCenter: React.FC<TradeAlertsNotificationCenterProps> = ({
  alerts = [],
  onMarkRead,
  onMarkAllRead,
  onDelete,
  onClearAll,
  soundEnabled = true,
  onSoundToggle,
  maxVisible = 50,
  compact = false,
}) => {
  const [filterType, setFilterType] = useState<AlertType | 'all'>('all');
  const [showUnreadOnly, setShowUnreadOnly] = useState(false);
  const [expandedId, setExpandedId] = useState<string | null>(null);

  const unreadCount = alerts.filter((a) => !a.read).length;

  // Filter alerts
  const filteredAlerts = useMemo(() => {
    let result = [...alerts];

    if (filterType !== 'all') {
      result = result.filter((a) => a.type === filterType);
    }

    if (showUnreadOnly) {
      result = result.filter((a) => !a.read);
    }

    return result.slice(0, maxVisible);
  }, [alerts, filterType, showUnreadOnly, maxVisible]);

  // Play sound for new critical alerts
  useEffect(() => {
    if (soundEnabled && alerts.length > 0) {
      const latestAlert = alerts[0];
      if (!latestAlert.read && latestAlert.priority === 'critical') {
        // In a real app, play notification sound
        console.log('Playing alert sound');
      }
    }
  }, [alerts, soundEnabled]);

  const getAlertIcon = (type: AlertType, priority: AlertPriority) => {
    switch (type) {
      case 'trade_opened':
      case 'order_filled':
        return <TrendingUp className="w-4 h-4 text-blue-400" />;
      case 'trade_closed':
        return <Check className="w-4 h-4 text-gray-400" />;
      case 'sl_hit':
        return <Shield className="w-4 h-4 text-red-400" />;
      case 'tp_hit':
        return <Target className="w-4 h-4 text-green-400" />;
      case 'margin_warning':
        return <AlertTriangle className="w-4 h-4 text-yellow-400" />;
      case 'margin_call':
        return <AlertTriangle className="w-4 h-4 text-red-400" />;
      case 'price_alert':
        return <Bell className="w-4 h-4 text-purple-400" />;
      case 'connection_lost':
        return <WifiOff className="w-4 h-4 text-red-400" />;
      case 'connection_restored':
        return <Wifi className="w-4 h-4 text-green-400" />;
      case 'order_rejected':
        return <X className="w-4 h-4 text-red-400" />;
      default:
        return <Bell className="w-4 h-4 text-gray-400" />;
    }
  };

  const getPriorityColor = (priority: AlertPriority) => {
    switch (priority) {
      case 'critical':
        return 'border-red-500/50 bg-red-500/10';
      case 'high':
        return 'border-orange-500/50 bg-orange-500/10';
      case 'medium':
        return 'border-yellow-500/50 bg-yellow-500/10';
      default:
        return 'border-gray-700 bg-gray-800/50';
    }
  };

  const formatTime = (timestamp: string) => {
    const date = new Date(timestamp);
    const now = new Date();
    const diff = now.getTime() - date.getTime();

    if (diff < 60000) return 'Just now';
    if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;
    if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;
    return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
  };

  const getTypeLabel = (type: AlertType) => {
    const labels: Record<AlertType, string> = {
      trade_opened: 'Trade Opened',
      trade_closed: 'Trade Closed',
      sl_hit: 'Stop Loss Hit',
      tp_hit: 'Take Profit Hit',
      margin_warning: 'Margin Warning',
      margin_call: 'Margin Call',
      price_alert: 'Price Alert',
      connection_lost: 'Disconnected',
      connection_restored: 'Connected',
      order_filled: 'Order Filled',
      order_rejected: 'Order Rejected',
    };
    return labels[type] || type;
  };

  return (
    <div className={`bg-gray-800/50 rounded-xl border border-gray-700 ${compact ? 'p-3' : 'p-4'}`}>
      {/* Header */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-3">
          <div className="relative">
            <Bell className="w-5 h-5 text-blue-400" />
            {unreadCount > 0 && (
              <span className="absolute -top-1 -right-1 w-4 h-4 bg-red-500 rounded-full text-[10px] text-white flex items-center justify-center font-bold">
                {unreadCount > 9 ? '9+' : unreadCount}
              </span>
            )}
          </div>
          <div>
            <h3 className="font-semibold text-white">Trade Alerts</h3>
            <p className="text-xs text-gray-500">{alerts.length} total • {unreadCount} unread</p>
          </div>
        </div>

        <div className="flex items-center gap-2">
          {/* Sound Toggle */}
          <button
            onClick={() => onSoundToggle?.(!soundEnabled)}
            className={`p-2 rounded-lg transition-colors ${
              soundEnabled
                ? 'text-blue-400 bg-blue-500/10'
                : 'text-gray-500 hover:bg-gray-700'
            }`}
            title={soundEnabled ? 'Sound On' : 'Sound Off'}
          >
            {soundEnabled ? <Volume2 className="w-4 h-4" /> : <VolumeX className="w-4 h-4" />}
          </button>

          {/* Mark All Read */}
          {unreadCount > 0 && (
            <button
              onClick={onMarkAllRead}
              className="p-2 text-gray-400 hover:text-white hover:bg-gray-700 rounded-lg transition-colors"
              title="Mark all as read"
            >
              <Check className="w-4 h-4" />
            </button>
          )}

          {/* Clear All */}
          {alerts.length > 0 && onClearAll && (
            <button
              onClick={onClearAll}
              className="p-2 text-gray-400 hover:text-red-400 hover:bg-gray-700 rounded-lg transition-colors"
              title="Clear all"
            >
              <Trash2 className="w-4 h-4" />
            </button>
          )}
        </div>
      </div>

      {/* Filters */}
      <div className="flex items-center gap-2 mb-4 overflow-x-auto pb-2">
        <Filter className="w-4 h-4 text-gray-500 flex-shrink-0" />
        <button
          onClick={() => setFilterType('all')}
          className={`px-2 py-1 text-xs rounded whitespace-nowrap ${
            filterType === 'all' ? 'bg-blue-600 text-white' : 'bg-gray-700 text-gray-300'
          }`}
        >
          All
        </button>
        <button
          onClick={() => setFilterType('trade_opened')}
          className={`px-2 py-1 text-xs rounded whitespace-nowrap ${
            filterType === 'trade_opened' ? 'bg-blue-600 text-white' : 'bg-gray-700 text-gray-300'
          }`}
        >
          Trades
        </button>
        <button
          onClick={() => setFilterType('sl_hit')}
          className={`px-2 py-1 text-xs rounded whitespace-nowrap ${
            filterType === 'sl_hit' ? 'bg-blue-600 text-white' : 'bg-gray-700 text-gray-300'
          }`}
        >
          SL/TP
        </button>
        <button
          onClick={() => setFilterType('margin_warning')}
          className={`px-2 py-1 text-xs rounded whitespace-nowrap ${
            filterType === 'margin_warning' ? 'bg-blue-600 text-white' : 'bg-gray-700 text-gray-300'
          }`}
        >
          Margin
        </button>
        <button
          onClick={() => setShowUnreadOnly(!showUnreadOnly)}
          className={`px-2 py-1 text-xs rounded whitespace-nowrap ${
            showUnreadOnly ? 'bg-blue-600 text-white' : 'bg-gray-700 text-gray-300'
          }`}
        >
          Unread
        </button>
      </div>

      {/* Alerts List */}
      {filteredAlerts.length === 0 ? (
        <div className="text-center py-8">
          <BellOff className="w-10 h-10 text-gray-600 mx-auto mb-2" />
          <p className="text-gray-400">No alerts</p>
        </div>
      ) : (
        <div className="space-y-2 max-h-[400px] overflow-y-auto">
          {filteredAlerts.map((alert) => (
            <div
              key={alert.id}
              onClick={() => {
                if (!alert.read) onMarkRead?.(alert.id);
                setExpandedId(expandedId === alert.id ? null : alert.id);
              }}
              className={`p-3 rounded-lg border cursor-pointer transition-all ${getPriorityColor(alert.priority)} ${
                !alert.read ? 'ring-1 ring-blue-500/30' : ''
              }`}
            >
              <div className="flex items-start gap-3">
                <div className="p-1.5 bg-gray-900/50 rounded-lg flex-shrink-0">
                  {getAlertIcon(alert.type, alert.priority)}
                </div>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center justify-between gap-2">
                    <div className="flex items-center gap-2">
                      <span className={`font-medium ${alert.read ? 'text-gray-400' : 'text-white'}`}>
                        {alert.title}
                      </span>
                      {!alert.read && (
                        <span className="w-2 h-2 bg-blue-500 rounded-full" />
                      )}
                    </div>
                    <span className="text-xs text-gray-500 flex-shrink-0">
                      {formatTime(alert.timestamp)}
                    </span>
                  </div>
                  <p className="text-sm text-gray-400 mt-0.5 truncate">{alert.message}</p>

                  {/* Expanded Content */}
                  {expandedId === alert.id && (
                    <div className="mt-3 pt-3 border-t border-gray-700/50">
                      <div className="flex flex-wrap gap-3 text-xs">
                        <div className="flex items-center gap-1">
                          <Clock className="w-3 h-3 text-gray-500" />
                          <span className="text-gray-400">
                            {new Date(alert.timestamp).toLocaleString()}
                          </span>
                        </div>
                        {alert.symbol && (
                          <div className="flex items-center gap-1">
                            <TrendingUp className="w-3 h-3 text-gray-500" />
                            <span className="text-gray-400">{alert.symbol}</span>
                          </div>
                        )}
                        {alert.ticket && (
                          <span className="text-gray-500">#{alert.ticket}</span>
                        )}
                        {alert.profit !== undefined && (
                          <div className="flex items-center gap-1">
                            <DollarSign className="w-3 h-3 text-gray-500" />
                            <span className={alert.profit >= 0 ? 'text-green-400' : 'text-red-400'}>
                              {alert.profit >= 0 ? '+' : ''}{alert.profit.toFixed(2)}
                            </span>
                          </div>
                        )}
                      </div>
                      {onDelete && (
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            onDelete(alert.id);
                          }}
                          className="mt-2 text-xs text-red-400 hover:text-red-300"
                        >
                          Delete alert
                        </button>
                      )}
                    </div>
                  )}
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Alert Type Legend */}
      {!compact && (
        <div className="mt-4 pt-4 border-t border-gray-700">
          <div className="flex flex-wrap gap-3 text-xs text-gray-500">
            <span className="flex items-center gap-1">
              <span className="w-2 h-2 bg-red-500 rounded-full" />
              Critical
            </span>
            <span className="flex items-center gap-1">
              <span className="w-2 h-2 bg-orange-500 rounded-full" />
              High
            </span>
            <span className="flex items-center gap-1">
              <span className="w-2 h-2 bg-yellow-500 rounded-full" />
              Medium
            </span>
            <span className="flex items-center gap-1">
              <span className="w-2 h-2 bg-gray-500 rounded-full" />
              Low
            </span>
          </div>
        </div>
      )}
    </div>
  );
};

export default TradeAlertsNotificationCenter;
