/**
 * RiskMonitor Component
 * Displays real-time risk metrics and warnings
 */

import React from 'react';
import {
  Shield,
  AlertTriangle,
  TrendingDown,
  Percent,
  DollarSign,
  Activity,
  BarChart3,
  AlertCircle,
  CheckCircle,
} from 'lucide-react';
import type { MT4Account, MT4Position } from '../../../services/trading.service';

interface RiskMetrics {
  totalExposure: number;
  marginUsed: number;
  marginLevel: number;
  unrealizedPnL: number;
  dailyPnL: number;
  dailyPnLPercent: number;
  maxDrawdown: number;
  openPositions: number;
  totalLots: number;
  largestPosition: number;
  riskPerTrade: number;
}

interface RiskMonitorProps {
  account: MT4Account | null;
  positions: MT4Position[];
  dailyStartBalance?: number;
  maxDailyLoss?: number;
  maxDrawdownLimit?: number;
  maxPositions?: number;
  maxLotSize?: number;
  compact?: boolean;
}

const RiskMonitor: React.FC<RiskMonitorProps> = ({
  account,
  positions,
  dailyStartBalance,
  maxDailyLoss = 5,
  maxDrawdownLimit = 10,
  maxPositions = 10,
  maxLotSize = 1.0,
  compact = false,
}) => {
  // Calculate risk metrics
  const calculateMetrics = (): RiskMetrics | null => {
    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 largestPosition = positions.length > 0
      ? Math.max(...positions.map(p => p.volume))
      : 0;

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

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

    // Simple exposure calculation (could be enhanced)
    const totalExposure = (account.margin / account.balance) * 100;

    return {
      totalExposure,
      marginUsed: account.margin,
      marginLevel,
      unrealizedPnL,
      dailyPnL,
      dailyPnLPercent,
      maxDrawdown: Math.min(0, dailyPnLPercent), // Simplified
      openPositions: positions.length,
      totalLots,
      largestPosition,
      riskPerTrade: totalLots > 0 ? (account.margin / positions.length) : 0,
    };
  };

  const metrics = calculateMetrics();

  // Risk level assessment
  const getRiskLevel = (): 'low' | 'medium' | 'high' | 'critical' => {
    if (!metrics) return 'low';

    if (
      metrics.marginLevel < 100 ||
      Math.abs(metrics.dailyPnLPercent) > maxDailyLoss ||
      metrics.openPositions > maxPositions
    ) {
      return 'critical';
    }

    if (
      metrics.marginLevel < 200 ||
      Math.abs(metrics.dailyPnLPercent) > maxDailyLoss * 0.7 ||
      metrics.totalExposure > 50
    ) {
      return 'high';
    }

    if (
      metrics.marginLevel < 500 ||
      Math.abs(metrics.dailyPnLPercent) > maxDailyLoss * 0.5 ||
      metrics.totalExposure > 30
    ) {
      return 'medium';
    }

    return 'low';
  };

  const riskLevel = getRiskLevel();

  const riskColors = {
    low: 'text-green-400',
    medium: 'text-yellow-400',
    high: 'text-orange-400',
    critical: 'text-red-400',
  };

  const riskBgColors = {
    low: 'bg-green-500/20 border-green-500/30',
    medium: 'bg-yellow-500/20 border-yellow-500/30',
    high: 'bg-orange-500/20 border-orange-500/30',
    critical: 'bg-red-500/20 border-red-500/30',
  };

  const riskLabels = {
    low: 'Low Risk',
    medium: 'Moderate',
    high: 'High Risk',
    critical: 'Critical',
  };

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

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

  if (compact) {
    return (
      <div className={`flex items-center gap-4 p-3 rounded-lg border ${riskBgColors[riskLevel]}`}>
        <div className="flex items-center gap-2">
          <Shield className={`w-5 h-5 ${riskColors[riskLevel]}`} />
          <span className={`font-medium ${riskColors[riskLevel]}`}>
            {riskLabels[riskLevel]}
          </span>
        </div>
        <div className="flex items-center gap-4 text-sm text-gray-400">
          <span>Margin: {metrics.marginLevel.toFixed(0)}%</span>
          <span>P&L: {metrics.dailyPnLPercent >= 0 ? '+' : ''}{metrics.dailyPnLPercent.toFixed(2)}%</span>
          <span>Positions: {metrics.openPositions}</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 ${riskBgColors[riskLevel]}`}>
        <div className="flex items-center gap-3">
          <div className={`p-2 rounded-lg ${riskBgColors[riskLevel]}`}>
            <Shield className={`w-5 h-5 ${riskColors[riskLevel]}`} />
          </div>
          <div>
            <h3 className="font-medium text-white">Risk Monitor</h3>
            <p className={`text-sm ${riskColors[riskLevel]}`}>{riskLabels[riskLevel]}</p>
          </div>
        </div>
        {riskLevel === '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">Warning</span>
          </div>
        )}
      </div>

      {/* Metrics Grid */}
      <div className="p-4 space-y-4">
        {/* Primary Metrics */}
        <div className="grid grid-cols-2 gap-4">
          {/* Margin Level */}
          <div className="p-3 bg-gray-900/50 rounded-lg">
            <div className="flex items-center gap-2 text-gray-400 text-sm mb-2">
              <Percent className="w-4 h-4" />
              <span>Margin Level</span>
            </div>
            <p className={`text-2xl font-bold ${
              metrics.marginLevel > 200 ? 'text-green-400' :
              metrics.marginLevel > 100 ? 'text-yellow-400' : 'text-red-400'
            }`}>
              {metrics.marginLevel > 9000 ? '∞' : `${metrics.marginLevel.toFixed(0)}%`}
            </p>
            <div className="mt-2 h-1.5 bg-gray-700 rounded-full overflow-hidden">
              <div
                className={`h-full rounded-full ${
                  metrics.marginLevel > 200 ? 'bg-green-500' :
                  metrics.marginLevel > 100 ? 'bg-yellow-500' : 'bg-red-500'
                }`}
                style={{ width: `${Math.min(metrics.marginLevel / 5, 100)}%` }}
              />
            </div>
          </div>

          {/* Daily P&L */}
          <div className="p-3 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>Daily P&L</span>
            </div>
            <p className={`text-2xl font-bold ${
              metrics.dailyPnL >= 0 ? 'text-green-400' : 'text-red-400'
            }`}>
              {metrics.dailyPnL >= 0 ? '+' : ''}{metrics.dailyPnLPercent.toFixed(2)}%
            </p>
            <p className={`text-sm ${
              metrics.dailyPnL >= 0 ? 'text-green-400/70' : 'text-red-400/70'
            }`}>
              {formatCurrency(metrics.dailyPnL)}
            </p>
          </div>
        </div>

        {/* Secondary Metrics */}
        <div className="grid grid-cols-3 gap-3">
          <div className="text-center p-3 bg-gray-900/50 rounded-lg">
            <Activity className="w-4 h-4 text-gray-400 mx-auto mb-1" />
            <p className="text-lg font-semibold text-white">{metrics.openPositions}</p>
            <p className="text-xs text-gray-500">Positions</p>
          </div>
          <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.totalLots.toFixed(2)}</p>
            <p className="text-xs text-gray-500">Total Lots</p>
          </div>
          <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.marginUsed)}
            </p>
            <p className="text-xs text-gray-500">Margin Used</p>
          </div>
        </div>

        {/* Risk Warnings */}
        <div className="space-y-2">
          {/* Daily Loss Limit */}
          <RiskIndicator
            label="Daily Loss Limit"
            current={Math.abs(metrics.dailyPnLPercent)}
            max={maxDailyLoss}
            unit="%"
            inverted
          />

          {/* Position Count */}
          <RiskIndicator
            label="Open Positions"
            current={metrics.openPositions}
            max={maxPositions}
            unit=""
          />

          {/* Largest Position */}
          <RiskIndicator
            label="Largest Position"
            current={metrics.largestPosition}
            max={maxLotSize}
            unit=" lots"
          />
        </div>

        {/* Warnings */}
        {riskLevel !== 'low' && (
          <div className={`p-3 rounded-lg border ${riskBgColors[riskLevel]}`}>
            <div className="flex items-start gap-2">
              <AlertCircle className={`w-5 h-5 flex-shrink-0 mt-0.5 ${riskColors[riskLevel]}`} />
              <div>
                <p className={`font-medium ${riskColors[riskLevel]}`}>Risk Warnings</p>
                <ul className="mt-1 space-y-1 text-sm text-gray-300">
                  {metrics.marginLevel < 200 && (
                    <li>• Margin level below 200%</li>
                  )}
                  {Math.abs(metrics.dailyPnLPercent) > maxDailyLoss * 0.7 && (
                    <li>• Approaching daily loss limit</li>
                  )}
                  {metrics.openPositions > maxPositions * 0.8 && (
                    <li>• Many open positions</li>
                  )}
                  {metrics.totalExposure > 30 && (
                    <li>• High account exposure</li>
                  )}
                </ul>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

// Risk Indicator Sub-component
interface RiskIndicatorProps {
  label: string;
  current: number;
  max: number;
  unit: string;
  inverted?: boolean;
}

const RiskIndicator: React.FC<RiskIndicatorProps> = ({
  label,
  current,
  max,
  unit,
  inverted = false,
}) => {
  const percentage = (current / max) * 100;
  const isWarning = inverted ? current > max * 0.7 : percentage > 70;
  const isDanger = inverted ? current > max : percentage > 100;

  return (
    <div className="flex items-center gap-3">
      <div className="flex-1">
        <div className="flex items-center justify-between text-sm mb-1">
          <span className="text-gray-400">{label}</span>
          <span className={`font-medium ${
            isDanger ? 'text-red-400' :
            isWarning ? 'text-yellow-400' : 'text-white'
          }`}>
            {current.toFixed(current < 10 ? 2 : 0)}{unit} / {max}{unit}
          </span>
        </div>
        <div className="h-1.5 bg-gray-700 rounded-full overflow-hidden">
          <div
            className={`h-full rounded-full transition-all ${
              isDanger ? 'bg-red-500' :
              isWarning ? 'bg-yellow-500' : 'bg-green-500'
            }`}
            style={{ width: `${Math.min(percentage, 100)}%` }}
          />
        </div>
      </div>
      {isDanger ? (
        <AlertTriangle className="w-4 h-4 text-red-400 flex-shrink-0" />
      ) : isWarning ? (
        <AlertCircle className="w-4 h-4 text-yellow-400 flex-shrink-0" />
      ) : (
        <CheckCircle className="w-4 h-4 text-green-400 flex-shrink-0" />
      )}
    </div>
  );
};

export default RiskMonitor;
