/**
 * AccountHealthDashboard Component
 * Unified view of account status and trading metrics
 */

import React, { useMemo } from 'react';
import {
  TrendingUp,
  TrendingDown,
  DollarSign,
  Percent,
  Activity,
  Award,
  AlertTriangle,
  Target,
  BarChart3,
  Clock,
  Zap,
} from 'lucide-react';
import type { MT4Account, MT4Position } from '../../../services/trading.service';

interface TradeStats {
  totalTrades: number;
  winningTrades: number;
  losingTrades: number;
  largestWin: number;
  largestLoss: number;
  consecutiveWins: number;
  consecutiveLosses: number;
}

interface AccountHealthDashboardProps {
  account: MT4Account | null;
  positions: MT4Position[];
  tradeStats?: TradeStats;
  dailyStartBalance?: number;
  compact?: boolean;
}

const AccountHealthDashboard: React.FC<AccountHealthDashboardProps> = ({
  account,
  positions,
  tradeStats,
  dailyStartBalance,
  compact = false,
}) => {
  // Calculate metrics
  const metrics = useMemo(() => {
    if (!account) return null;

    const unrealizedPnL = positions.reduce((sum, p) => sum + p.profit, 0);
    const totalLots = positions.reduce((sum, p) => sum + p.volume, 0);

    const drawdown = dailyStartBalance
      ? ((dailyStartBalance - account.equity) / dailyStartBalance) * 100
      : ((account.balance - account.equity) / account.balance) * 100;

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

    const marginUsagePercent = account.balance > 0
      ? (account.margin / account.balance) * 100
      : 0;

    const winRate = tradeStats && tradeStats.totalTrades > 0
      ? (tradeStats.winningTrades / tradeStats.totalTrades) * 100
      : null;

    const profitFactor = tradeStats && tradeStats.largestLoss !== 0
      ? Math.abs(tradeStats.largestWin / tradeStats.largestLoss)
      : null;

    return {
      equity: account.equity,
      balance: account.balance,
      freeMargin: account.free_margin,
      marginUsed: account.margin,
      marginLevel,
      marginUsagePercent,
      unrealizedPnL,
      drawdown: Math.max(0, drawdown),
      totalLots,
      positionCount: positions.length,
      winRate,
      profitFactor,
    };
  }, [account, positions, dailyStartBalance, tradeStats]);

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

  // Get health status
  const getHealthStatus = (): 'excellent' | 'good' | 'warning' | 'critical' => {
    if (!metrics) return 'warning';

    if (
      metrics.marginLevel < 150 ||
      metrics.drawdown > 10 ||
      metrics.marginUsagePercent > 50
    ) {
      return 'critical';
    }

    if (
      metrics.marginLevel < 300 ||
      metrics.drawdown > 5 ||
      metrics.marginUsagePercent > 30
    ) {
      return 'warning';
    }

    if (
      metrics.marginLevel > 500 &&
      metrics.drawdown < 3 &&
      metrics.marginUsagePercent < 20
    ) {
      return 'excellent';
    }

    return 'good';
  };

  const healthStatus = getHealthStatus();

  const healthColors = {
    excellent: 'text-green-400 bg-green-500/20 border-green-500/30',
    good: 'text-blue-400 bg-blue-500/20 border-blue-500/30',
    warning: 'text-yellow-400 bg-yellow-500/20 border-yellow-500/30',
    critical: 'text-red-400 bg-red-500/20 border-red-500/30',
  };

  const healthLabels = {
    excellent: 'Excellent',
    good: 'Good',
    warning: 'Caution',
    critical: 'At Risk',
  };

  if (!account || !metrics) {
    return (
      <div className="bg-gray-800 rounded-xl border border-gray-700 p-6 text-center">
        <Activity className="w-10 h-10 text-gray-500 mx-auto mb-3" />
        <h4 className="font-medium text-white mb-1">Account Health</h4>
        <p className="text-sm text-gray-400">Connect MT4 to view metrics</p>
      </div>
    );
  }

  if (compact) {
    return (
      <div className={`flex items-center gap-4 p-3 rounded-lg border ${healthColors[healthStatus]}`}>
        <div className="flex items-center gap-2">
          <Activity className={`w-5 h-5 ${healthColors[healthStatus].split(' ')[0]}`} />
          <span className={`font-medium ${healthColors[healthStatus].split(' ')[0]}`}>
            {healthLabels[healthStatus]}
          </span>
        </div>
        <div className="flex items-center gap-4 text-sm text-gray-400">
          <span>Equity: {formatCurrency(metrics.equity)}</span>
          <span>DD: {metrics.drawdown.toFixed(1)}%</span>
          <span>Margin: {metrics.marginLevel > 9000 ? '∞' : `${metrics.marginLevel.toFixed(0)}%`}</span>
        </div>
      </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 ${healthColors[healthStatus]}`}>
        <div className="flex items-center gap-3">
          <div className={`p-2 rounded-lg ${healthColors[healthStatus]}`}>
            <Activity className={`w-5 h-5 ${healthColors[healthStatus].split(' ')[0]}`} />
          </div>
          <div>
            <h3 className="font-medium text-white">Account Health</h3>
            <p className={`text-sm ${healthColors[healthStatus].split(' ')[0]}`}>
              {healthLabels[healthStatus]}
            </p>
          </div>
        </div>
        {healthStatus === 'critical' && (
          <div className="flex items-center gap-2 px-3 py-1 bg-red-500/30 rounded-full">
            <AlertTriangle className="w-4 h-4 text-red-400" />
            <span className="text-sm text-red-400 font-medium">High Risk</span>
          </div>
        )}
      </div>

      <div className="p-4 space-y-4">
        {/* Main Metrics */}
        <div className="grid grid-cols-2 gap-4">
          {/* Equity vs Balance */}
          <div className="p-4 bg-gray-900/50 rounded-lg">
            <div className="flex items-center gap-2 text-gray-400 text-sm mb-2">
              <DollarSign className="w-4 h-4" />
              <span>Equity / Balance</span>
            </div>
            <p className={`text-2xl font-bold ${
              metrics.equity >= metrics.balance ? 'text-green-400' : 'text-red-400'
            }`}>
              {formatCurrency(metrics.equity)}
            </p>
            <p className="text-sm text-gray-400">
              of {formatCurrency(metrics.balance)}
            </p>
            {metrics.unrealizedPnL !== 0 && (
              <p className={`text-xs mt-1 ${
                metrics.unrealizedPnL >= 0 ? 'text-green-400' : 'text-red-400'
              }`}>
                Floating: {metrics.unrealizedPnL >= 0 ? '+' : ''}{formatCurrency(metrics.unrealizedPnL)}
              </p>
            )}
          </div>

          {/* Drawdown */}
          <div className="p-4 bg-gray-900/50 rounded-lg">
            <div className="flex items-center gap-2 text-gray-400 text-sm mb-2">
              <TrendingDown className="w-4 h-4" />
              <span>Drawdown</span>
            </div>
            <p className={`text-2xl font-bold ${
              metrics.drawdown < 3 ? 'text-green-400' :
              metrics.drawdown < 7 ? 'text-yellow-400' : 'text-red-400'
            }`}>
              {metrics.drawdown.toFixed(2)}%
            </p>
            <div className="mt-2 h-2 bg-gray-700 rounded-full overflow-hidden">
              <div
                className={`h-full rounded-full transition-all ${
                  metrics.drawdown < 3 ? 'bg-green-500' :
                  metrics.drawdown < 7 ? 'bg-yellow-500' : 'bg-red-500'
                }`}
                style={{ width: `${Math.min(metrics.drawdown * 10, 100)}%` }}
              />
            </div>
          </div>
        </div>

        {/* Secondary Metrics */}
        <div className="grid grid-cols-4 gap-3">
          {/* Margin Level */}
          <div className="text-center p-3 bg-gray-900/50 rounded-lg">
            <Percent className="w-4 h-4 text-gray-400 mx-auto mb-1" />
            <p className={`text-lg font-semibold ${
              metrics.marginLevel > 300 ? 'text-green-400' :
              metrics.marginLevel > 150 ? 'text-yellow-400' : 'text-red-400'
            }`}>
              {metrics.marginLevel > 9000 ? '∞' : `${metrics.marginLevel.toFixed(0)}%`}
            </p>
            <p className="text-xs text-gray-500">Margin Level</p>
          </div>

          {/* Free Margin */}
          <div className="text-center p-3 bg-gray-900/50 rounded-lg">
            <DollarSign className="w-4 h-4 text-gray-400 mx-auto mb-1" />
            <p className="text-lg font-semibold text-white">
              {formatCurrency(metrics.freeMargin)}
            </p>
            <p className="text-xs text-gray-500">Free Margin</p>
          </div>

          {/* Positions */}
          <div className="text-center p-3 bg-gray-900/50 rounded-lg">
            <BarChart3 className="w-4 h-4 text-gray-400 mx-auto mb-1" />
            <p className="text-lg font-semibold text-white">{metrics.positionCount}</p>
            <p className="text-xs text-gray-500">Positions</p>
          </div>

          {/* Total Lots */}
          <div className="text-center p-3 bg-gray-900/50 rounded-lg">
            <Target className="w-4 h-4 text-gray-400 mx-auto mb-1" />
            <p className="text-lg font-semibold text-white">{metrics.totalLots.toFixed(2)}</p>
            <p className="text-xs text-gray-500">Total Lots</p>
          </div>
        </div>

        {/* Trade Stats */}
        {tradeStats && tradeStats.totalTrades > 0 && (
          <div className="p-4 bg-gray-900/50 rounded-lg">
            <h4 className="text-sm font-medium text-white mb-3 flex items-center gap-2">
              <Award className="w-4 h-4 text-yellow-400" />
              Trading Performance
            </h4>
            <div className="grid grid-cols-3 gap-4">
              {/* Win Rate */}
              <div>
                <p className="text-xs text-gray-500 mb-1">Win Rate</p>
                <p className={`text-lg font-bold ${
                  metrics.winRate && metrics.winRate >= 50 ? 'text-green-400' : 'text-red-400'
                }`}>
                  {metrics.winRate?.toFixed(1)}%
                </p>
                <p className="text-xs text-gray-500">
                  {tradeStats.winningTrades}W / {tradeStats.losingTrades}L
                </p>
              </div>

              {/* Profit Factor */}
              <div>
                <p className="text-xs text-gray-500 mb-1">Profit Factor</p>
                <p className={`text-lg font-bold ${
                  metrics.profitFactor && metrics.profitFactor >= 1.5 ? 'text-green-400' :
                  metrics.profitFactor && metrics.profitFactor >= 1 ? 'text-yellow-400' : 'text-red-400'
                }`}>
                  {metrics.profitFactor?.toFixed(2) || '-'}
                </p>
              </div>

              {/* Streak */}
              <div>
                <p className="text-xs text-gray-500 mb-1">Current Streak</p>
                {tradeStats.consecutiveWins > 0 ? (
                  <div className="flex items-center gap-1">
                    <Zap className="w-4 h-4 text-green-400" />
                    <span className="text-lg font-bold text-green-400">
                      {tradeStats.consecutiveWins}W
                    </span>
                  </div>
                ) : tradeStats.consecutiveLosses > 0 ? (
                  <div className="flex items-center gap-1">
                    <TrendingDown className="w-4 h-4 text-red-400" />
                    <span className="text-lg font-bold text-red-400">
                      {tradeStats.consecutiveLosses}L
                    </span>
                  </div>
                ) : (
                  <span className="text-lg font-bold text-gray-400">-</span>
                )}
              </div>
            </div>

            {/* Best/Worst Trade */}
            <div className="flex items-center justify-between mt-3 pt-3 border-t border-gray-700">
              <div className="flex items-center gap-2">
                <TrendingUp className="w-4 h-4 text-green-400" />
                <span className="text-sm text-gray-400">Best:</span>
                <span className="text-sm text-green-400 font-medium">
                  +{formatCurrency(tradeStats.largestWin)}
                </span>
              </div>
              <div className="flex items-center gap-2">
                <TrendingDown className="w-4 h-4 text-red-400" />
                <span className="text-sm text-gray-400">Worst:</span>
                <span className="text-sm text-red-400 font-medium">
                  {formatCurrency(tradeStats.largestLoss)}
                </span>
              </div>
            </div>
          </div>
        )}

        {/* Warnings */}
        {healthStatus !== 'excellent' && healthStatus !== 'good' && (
          <div className={`p-3 rounded-lg border ${healthColors[healthStatus]}`}>
            <div className="flex items-start gap-2">
              <AlertTriangle className={`w-5 h-5 flex-shrink-0 mt-0.5 ${healthColors[healthStatus].split(' ')[0]}`} />
              <div>
                <p className={`font-medium ${healthColors[healthStatus].split(' ')[0]}`}>
                  Health Warnings
                </p>
                <ul className="mt-1 space-y-1 text-sm text-gray-300">
                  {metrics.marginLevel < 300 && (
                    <li>• Margin level below 300%</li>
                  )}
                  {metrics.drawdown > 5 && (
                    <li>• Drawdown exceeds 5%</li>
                  )}
                  {metrics.marginUsagePercent > 30 && (
                    <li>• High margin usage ({metrics.marginUsagePercent.toFixed(0)}%)</li>
                  )}
                  {metrics.positionCount > 5 && (
                    <li>• Multiple open positions</li>
                  )}
                </ul>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default AccountHealthDashboard;
