/**
 * MT4ConnectionStatus Component
 * Displays MT4 broker connection status with account info
 */

import React, { useEffect, useState, useCallback } from 'react';
import {
  Wifi,
  WifiOff,
  RefreshCw,
  AlertTriangle,
  CheckCircle,
  Server,
  DollarSign,
  TrendingUp,
  Settings,
} from 'lucide-react';
import { getMT4Account, type MT4Account } from '../../../services/trading.service';

interface MT4ConnectionStatusProps {
  onAccountLoad?: (account: MT4Account | null) => void;
  onSettingsClick?: () => void;
  compact?: boolean;
  autoRefresh?: boolean;
  refreshInterval?: number;
}

type ConnectionState = 'connecting' | 'connected' | 'disconnected' | 'error';

const MT4ConnectionStatus: React.FC<MT4ConnectionStatusProps> = ({
  onAccountLoad,
  onSettingsClick,
  compact = false,
  autoRefresh = true,
  refreshInterval = 30000,
}) => {
  const [connectionState, setConnectionState] = useState<ConnectionState>('connecting');
  const [account, setAccount] = useState<MT4Account | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [lastUpdate, setLastUpdate] = useState<Date | null>(null);
  const [isRefreshing, setIsRefreshing] = useState(false);

  const fetchAccount = useCallback(async () => {
    setIsRefreshing(true);
    try {
      const data = await getMT4Account();
      if (data && data.connected) {
        setAccount(data);
        setConnectionState('connected');
        setError(null);
        onAccountLoad?.(data);
      } else if (data && !data.connected) {
        setAccount(data);
        setConnectionState('disconnected');
        setError('MT4 terminal not connected');
        onAccountLoad?.(null);
      } else {
        setConnectionState('disconnected');
        setError('No MT4 account configured');
        onAccountLoad?.(null);
      }
      setLastUpdate(new Date());
    } catch (err) {
      setConnectionState('error');
      setError(err instanceof Error ? err.message : 'Connection error');
      onAccountLoad?.(null);
    } finally {
      setIsRefreshing(false);
    }
  }, [onAccountLoad]);

  useEffect(() => {
    fetchAccount();

    if (autoRefresh) {
      const interval = setInterval(fetchAccount, refreshInterval);
      return () => clearInterval(interval);
    }
  }, [fetchAccount, autoRefresh, refreshInterval]);

  const getStatusColor = () => {
    switch (connectionState) {
      case 'connected':
        return 'text-green-400';
      case 'connecting':
        return 'text-yellow-400';
      case 'disconnected':
        return 'text-gray-400';
      case 'error':
        return 'text-red-400';
    }
  };

  const getStatusIcon = () => {
    switch (connectionState) {
      case 'connected':
        return <Wifi className="w-4 h-4" />;
      case 'connecting':
        return <RefreshCw className="w-4 h-4 animate-spin" />;
      case 'disconnected':
        return <WifiOff className="w-4 h-4" />;
      case 'error':
        return <AlertTriangle className="w-4 h-4" />;
    }
  };

  const getStatusText = () => {
    switch (connectionState) {
      case 'connected':
        return 'Connected';
      case 'connecting':
        return 'Connecting...';
      case 'disconnected':
        return 'Disconnected';
      case 'error':
        return 'Error';
    }
  };

  const formatCurrency = (value: number, currency: string = 'USD') => {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: currency,
      minimumFractionDigits: 2,
    }).format(value);
  };

  const marginLevel = account?.margin && account.margin > 0
    ? ((account.equity / account.margin) * 100)
    : null;

  if (compact) {
    return (
      <div className="flex items-center gap-2">
        <div className={`flex items-center gap-1.5 ${getStatusColor()}`}>
          {getStatusIcon()}
          <span className="text-sm font-medium">{getStatusText()}</span>
        </div>
        {connectionState === 'connected' && account && (
          <span className="text-sm text-gray-400">
            {formatCurrency(account.balance, account.currency)}
          </span>
        )}
        <button
          onClick={fetchAccount}
          disabled={isRefreshing}
          className="p-1 text-gray-400 hover:text-white transition-colors disabled:opacity-50"
          title="Refresh"
        >
          <RefreshCw className={`w-3.5 h-3.5 ${isRefreshing ? 'animate-spin' : ''}`} />
        </button>
      </div>
    );
  }

  return (
    <div className="bg-gray-800 rounded-xl border border-gray-700 overflow-hidden">
      {/* Header */}
      <div className="flex items-center justify-between p-4 border-b border-gray-700">
        <div className="flex items-center gap-3">
          <div className={`p-2 rounded-lg ${
            connectionState === 'connected' ? 'bg-green-500/20' : 'bg-gray-700'
          }`}>
            <Server className={`w-5 h-5 ${getStatusColor()}`} />
          </div>
          <div>
            <h3 className="font-medium text-white">MT4 Connection</h3>
            <div className={`flex items-center gap-1.5 text-sm ${getStatusColor()}`}>
              {getStatusIcon()}
              <span>{getStatusText()}</span>
            </div>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={fetchAccount}
            disabled={isRefreshing}
            className="p-2 text-gray-400 hover:text-white hover:bg-gray-700 rounded-lg transition-colors disabled:opacity-50"
            title="Refresh connection"
          >
            <RefreshCw className={`w-4 h-4 ${isRefreshing ? 'animate-spin' : ''}`} />
          </button>
          {onSettingsClick && (
            <button
              onClick={onSettingsClick}
              className="p-2 text-gray-400 hover:text-white hover:bg-gray-700 rounded-lg transition-colors"
              title="Connection settings"
            >
              <Settings className="w-4 h-4" />
            </button>
          )}
        </div>
      </div>

      {/* Content */}
      {connectionState === 'connected' && account ? (
        <div className="p-4 space-y-4">
          {/* Broker Info */}
          <div className="flex items-center justify-between text-sm">
            <span className="text-gray-400">Broker</span>
            <span className="text-white font-medium">{account.broker}</span>
          </div>
          <div className="flex items-center justify-between text-sm">
            <span className="text-gray-400">Account</span>
            <span className="text-white font-mono">{account.account_id}</span>
          </div>
          <div className="flex items-center justify-between text-sm">
            <span className="text-gray-400">Leverage</span>
            <span className="text-white">1:{account.leverage}</span>
          </div>

          <div className="border-t border-gray-700 pt-4 space-y-3">
            {/* Balance */}
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2 text-gray-400">
                <DollarSign className="w-4 h-4" />
                <span className="text-sm">Balance</span>
              </div>
              <span className="text-white font-medium">
                {formatCurrency(account.balance, account.currency)}
              </span>
            </div>

            {/* Equity */}
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2 text-gray-400">
                <TrendingUp className="w-4 h-4" />
                <span className="text-sm">Equity</span>
              </div>
              <span className={`font-medium ${
                account.equity >= account.balance ? 'text-green-400' : 'text-red-400'
              }`}>
                {formatCurrency(account.equity, account.currency)}
              </span>
            </div>

            {/* Free Margin */}
            <div className="flex items-center justify-between">
              <span className="text-sm text-gray-400">Free Margin</span>
              <span className="text-white">
                {formatCurrency(account.free_margin, account.currency)}
              </span>
            </div>

            {/* Margin Level */}
            {marginLevel !== null && account.margin > 0 && (
              <div className="pt-2">
                <div className="flex items-center justify-between text-sm mb-1">
                  <span className="text-gray-400">Margin Level</span>
                  <span className={`font-medium ${
                    marginLevel > 200 ? 'text-green-400' :
                    marginLevel > 100 ? 'text-yellow-400' : 'text-red-400'
                  }`}>
                    {marginLevel.toFixed(0)}%
                  </span>
                </div>
                <div className="h-2 bg-gray-700 rounded-full overflow-hidden">
                  <div
                    className={`h-full rounded-full transition-all ${
                      marginLevel > 200 ? 'bg-green-500' :
                      marginLevel > 100 ? 'bg-yellow-500' : 'bg-red-500'
                    }`}
                    style={{ width: `${Math.min(marginLevel / 5, 100)}%` }}
                  />
                </div>
              </div>
            )}
          </div>

          {/* Last Update */}
          {lastUpdate && (
            <p className="text-xs text-gray-500 pt-2">
              Last updated: {lastUpdate.toLocaleTimeString()}
            </p>
          )}
        </div>
      ) : connectionState === 'error' || connectionState === 'disconnected' ? (
        <div className="p-6 text-center">
          <div className={`w-12 h-12 rounded-full ${
            connectionState === 'error' ? 'bg-red-500/20' : 'bg-gray-700'
          } flex items-center justify-center mx-auto mb-3`}>
            {connectionState === 'error' ? (
              <AlertTriangle className="w-6 h-6 text-red-400" />
            ) : (
              <WifiOff className="w-6 h-6 text-gray-400" />
            )}
          </div>
          <h4 className="font-medium text-white mb-1">
            {connectionState === 'error' ? 'Connection Error' : 'Not Connected'}
          </h4>
          <p className="text-sm text-gray-400 mb-4">
            {error || 'MT4 terminal is not connected'}
          </p>
          <button
            onClick={fetchAccount}
            className="px-4 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-lg text-sm transition-colors"
          >
            Retry Connection
          </button>
        </div>
      ) : (
        <div className="p-6 flex items-center justify-center">
          <RefreshCw className="w-6 h-6 text-blue-400 animate-spin" />
        </div>
      )}
    </div>
  );
};

export default MT4ConnectionStatus;
