/**
 * TradingMetricsCard Component
 * Display daily/session trading performance metrics
 */

import React, { useMemo } from 'react';
import {
  BarChart3,
  TrendingUp,
  TrendingDown,
  Target,
  Award,
  Flame,
  Clock,
  DollarSign,
  Percent,
  ArrowUpCircle,
  ArrowDownCircle,
} from 'lucide-react';

interface DailyMetrics {
  date: string;
  totalTrades: number;
  winningTrades: number;
  losingTrades: number;
  grossProfit: number;
  grossLoss: number;
  netProfit: number;
  commission: number;
  swap: number;
  pips: number;
  volume: number; // total lots
  largestWin: number;
  largestLoss: number;
  avgWin: number;
  avgLoss: number;
  consecutiveWins: number;
  consecutiveLosses: number;
  tradingHours: number;
}

interface TradingMetricsCardProps {
  metrics: DailyMetrics;
  previousMetrics?: DailyMetrics;
  showComparison?: boolean;
  compact?: boolean;
}

const TradingMetricsCard: React.FC<TradingMetricsCardProps> = ({
  metrics,
  previousMetrics,
  showComparison = true,
  compact = false,
}) => {
  const winRate = metrics.totalTrades > 0
    ? (metrics.winningTrades / metrics.totalTrades) * 100
    : 0;

  const profitFactor = metrics.grossLoss > 0
    ? Math.abs(metrics.grossProfit / metrics.grossLoss)
    : metrics.grossProfit > 0 ? Infinity : 0;

  const expectancy = metrics.totalTrades > 0
    ? metrics.netProfit / metrics.totalTrades
    : 0;

  const riskRewardRatio = metrics.avgLoss > 0
    ? metrics.avgWin / Math.abs(metrics.avgLoss)
    : metrics.avgWin > 0 ? Infinity : 0;

  // Comparison calculations
  const comparison = useMemo(() => {
    if (!previousMetrics || !showComparison) return null;

    const prevWinRate = previousMetrics.totalTrades > 0
      ? (previousMetrics.winningTrades / previousMetrics.totalTrades) * 100
      : 0;

    return {
      netProfitChange: metrics.netProfit - previousMetrics.netProfit,
      winRateChange: winRate - prevWinRate,
      tradesChange: metrics.totalTrades - previousMetrics.totalTrades,
      pipsChange: metrics.pips - previousMetrics.pips,
    };
  }, [metrics, previousMetrics, showComparison, winRate]);

  const formatChange = (value: number, suffix: string = '') => {
    const sign = value >= 0 ? '+' : '';
    return `${sign}${value.toFixed(value % 1 === 0 ? 0 : 1)}${suffix}`;
  };

  const ChangeIndicator = ({ value, suffix = '' }: { value: number; suffix?: string }) => (
    <span className={`text-xs ${value >= 0 ? 'text-green-400' : 'text-red-400'}`}>
      {formatChange(value, suffix)}
    </span>
  );

  if (compact) {
    return (
      <div className="p-3 bg-gray-800/50 rounded-lg border border-gray-700">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <BarChart3 className="w-4 h-4 text-blue-400" />
            <span className="text-sm text-gray-400">Today</span>
          </div>
          <div className={`font-bold ${metrics.netProfit >= 0 ? 'text-green-400' : 'text-red-400'}`}>
            {metrics.netProfit >= 0 ? '+' : ''}{metrics.netProfit.toFixed(2)}
          </div>
        </div>
        <div className="flex items-center justify-between mt-2 text-xs text-gray-500">
          <span>{metrics.totalTrades} trades</span>
          <span>{winRate.toFixed(0)}% win</span>
          <span>{metrics.pips >= 0 ? '+' : ''}{metrics.pips} pips</span>
        </div>
      </div>
    );
  }

  return (
    <div className="p-4 bg-gray-800/50 rounded-xl border border-gray-700">
      {/* Header */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-2">
          <BarChart3 className="w-5 h-5 text-blue-400" />
          <h3 className="font-semibold text-white">Daily Metrics</h3>
        </div>
        <div className="text-sm text-gray-500">
          {new Date(metrics.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}
        </div>
      </div>

      {/* Main P&L */}
      <div className="text-center p-4 bg-gray-900/50 rounded-lg mb-4">
        <div className={`text-3xl font-bold ${metrics.netProfit >= 0 ? 'text-green-400' : 'text-red-400'}`}>
          {metrics.netProfit >= 0 ? '+' : ''}${metrics.netProfit.toFixed(2)}
        </div>
        <div className="text-sm text-gray-500 mt-1">Net Profit/Loss</div>
        {comparison && (
          <div className="mt-2">
            <ChangeIndicator value={comparison.netProfitChange} suffix=" vs yesterday" />
          </div>
        )}
      </div>

      {/* Key Stats Grid */}
      <div className="grid grid-cols-3 gap-3 mb-4">
        {/* Win Rate */}
        <div className="p-3 bg-gray-900/50 rounded-lg text-center">
          <div className="flex items-center justify-center gap-1 mb-1">
            <Target className="w-4 h-4 text-blue-400" />
          </div>
          <div className="text-lg font-bold text-white">{winRate.toFixed(1)}%</div>
          <div className="text-xs text-gray-500">Win Rate</div>
          {comparison && <ChangeIndicator value={comparison.winRateChange} suffix="%" />}
        </div>

        {/* Profit Factor */}
        <div className="p-3 bg-gray-900/50 rounded-lg text-center">
          <div className="flex items-center justify-center gap-1 mb-1">
            <Award className="w-4 h-4 text-yellow-400" />
          </div>
          <div className="text-lg font-bold text-white">
            {profitFactor === Infinity ? '∞' : profitFactor.toFixed(2)}
          </div>
          <div className="text-xs text-gray-500">Profit Factor</div>
        </div>

        {/* Total Trades */}
        <div className="p-3 bg-gray-900/50 rounded-lg text-center">
          <div className="flex items-center justify-center gap-1 mb-1">
            <TrendingUp className="w-4 h-4 text-green-400" />
          </div>
          <div className="text-lg font-bold text-white">{metrics.totalTrades}</div>
          <div className="text-xs text-gray-500">Trades</div>
          {comparison && <ChangeIndicator value={comparison.tradesChange} />}
        </div>
      </div>

      {/* Win/Loss Breakdown */}
      <div className="flex items-center gap-2 mb-4">
        <div className="flex-1 bg-gray-900/50 rounded-lg p-3">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <ArrowUpCircle className="w-4 h-4 text-green-400" />
              <span className="text-sm text-gray-400">Winners</span>
            </div>
            <span className="text-green-400 font-medium">{metrics.winningTrades}</span>
          </div>
          <div className="mt-2 text-xs text-gray-500">
            Gross: <span className="text-green-400">+${metrics.grossProfit.toFixed(2)}</span>
          </div>
        </div>
        <div className="flex-1 bg-gray-900/50 rounded-lg p-3">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <ArrowDownCircle className="w-4 h-4 text-red-400" />
              <span className="text-sm text-gray-400">Losers</span>
            </div>
            <span className="text-red-400 font-medium">{metrics.losingTrades}</span>
          </div>
          <div className="mt-2 text-xs text-gray-500">
            Gross: <span className="text-red-400">${metrics.grossLoss.toFixed(2)}</span>
          </div>
        </div>
      </div>

      {/* Detailed Stats */}
      <div className="space-y-2">
        <div className="flex items-center justify-between py-2 border-b border-gray-700/50">
          <div className="flex items-center gap-2 text-sm text-gray-400">
            <DollarSign className="w-4 h-4" />
            <span>Avg Win / Loss</span>
          </div>
          <div className="text-sm">
            <span className="text-green-400">${metrics.avgWin.toFixed(2)}</span>
            <span className="text-gray-600"> / </span>
            <span className="text-red-400">${Math.abs(metrics.avgLoss).toFixed(2)}</span>
          </div>
        </div>

        <div className="flex items-center justify-between py-2 border-b border-gray-700/50">
          <div className="flex items-center gap-2 text-sm text-gray-400">
            <Percent className="w-4 h-4" />
            <span>R:R Ratio</span>
          </div>
          <div className="text-sm text-white">
            {riskRewardRatio === Infinity ? '∞' : riskRewardRatio.toFixed(2)}
          </div>
        </div>

        <div className="flex items-center justify-between py-2 border-b border-gray-700/50">
          <div className="flex items-center gap-2 text-sm text-gray-400">
            <TrendingUp className="w-4 h-4" />
            <span>Total Pips</span>
          </div>
          <div className={`text-sm font-mono ${metrics.pips >= 0 ? 'text-green-400' : 'text-red-400'}`}>
            {metrics.pips >= 0 ? '+' : ''}{metrics.pips}
          </div>
        </div>

        <div className="flex items-center justify-between py-2 border-b border-gray-700/50">
          <div className="flex items-center gap-2 text-sm text-gray-400">
            <BarChart3 className="w-4 h-4" />
            <span>Volume</span>
          </div>
          <div className="text-sm text-white">{metrics.volume.toFixed(2)} lots</div>
        </div>

        <div className="flex items-center justify-between py-2 border-b border-gray-700/50">
          <div className="flex items-center gap-2 text-sm text-gray-400">
            <Clock className="w-4 h-4" />
            <span>Trading Time</span>
          </div>
          <div className="text-sm text-white">{metrics.tradingHours.toFixed(1)}h</div>
        </div>

        <div className="flex items-center justify-between py-2 border-b border-gray-700/50">
          <div className="flex items-center gap-2 text-sm text-gray-400">
            <DollarSign className="w-4 h-4" />
            <span>Expectancy</span>
          </div>
          <div className={`text-sm font-mono ${expectancy >= 0 ? 'text-green-400' : 'text-red-400'}`}>
            ${expectancy.toFixed(2)}/trade
          </div>
        </div>
      </div>

      {/* Streaks & Records */}
      <div className="grid grid-cols-2 gap-3 mt-4">
        <div className="p-3 bg-gray-900/50 rounded-lg">
          <div className="flex items-center gap-2 mb-2">
            <Flame className="w-4 h-4 text-orange-400" />
            <span className="text-xs text-gray-400">Best Trade</span>
          </div>
          <div className="text-green-400 font-bold">+${metrics.largestWin.toFixed(2)}</div>
        </div>
        <div className="p-3 bg-gray-900/50 rounded-lg">
          <div className="flex items-center gap-2 mb-2">
            <TrendingDown className="w-4 h-4 text-red-400" />
            <span className="text-xs text-gray-400">Worst Trade</span>
          </div>
          <div className="text-red-400 font-bold">${metrics.largestLoss.toFixed(2)}</div>
        </div>
      </div>

      {/* Consecutive Streaks */}
      <div className="flex items-center justify-center gap-4 mt-4 pt-4 border-t border-gray-700/50">
        <div className="text-center">
          <div className="text-xs text-gray-500 mb-1">Win Streak</div>
          <div className="text-green-400 font-bold">{metrics.consecutiveWins}</div>
        </div>
        <div className="w-px h-8 bg-gray-700" />
        <div className="text-center">
          <div className="text-xs text-gray-500 mb-1">Loss Streak</div>
          <div className="text-red-400 font-bold">{metrics.consecutiveLosses}</div>
        </div>
      </div>

      {/* Fees */}
      {(metrics.commission !== 0 || metrics.swap !== 0) && (
        <div className="mt-4 pt-3 border-t border-gray-700/50 text-xs text-gray-500">
          <div className="flex justify-between">
            <span>Commission:</span>
            <span className="text-gray-400">${metrics.commission.toFixed(2)}</span>
          </div>
          <div className="flex justify-between mt-1">
            <span>Swap:</span>
            <span className="text-gray-400">${metrics.swap.toFixed(2)}</span>
          </div>
        </div>
      )}
    </div>
  );
};

export default TradingMetricsCard;
