/**
 * Risk Analytics Component
 * Comprehensive risk analysis dashboard with Sharpe ratio,
 * Beta calculation, drawdown analysis, and risk metrics
 */

import React, { useState, useEffect, useMemo } from 'react';
import {
  ShieldExclamationIcon,
  ChartBarIcon,
  ArrowTrendingDownIcon,
  InformationCircleIcon,
  ArrowPathIcon,
  ExclamationTriangleIcon,
} from '@heroicons/react/24/solid';
import type { PortfolioMetrics, PortfolioAllocation } from '../../../services/portfolio.service';

interface RiskAnalyticsProps {
  portfolioId: string;
  allocations?: PortfolioAllocation[];
  metrics?: PortfolioMetrics | null;
  compact?: boolean;
}

interface DrawdownPeriod {
  startDate: string;
  endDate: string;
  duration: number;
  peakValue: number;
  troughValue: number;
  drawdownPercent: number;
  recovered: boolean;
}

interface RiskRating {
  level: 'low' | 'moderate' | 'high' | 'very-high';
  score: number;
  label: string;
  color: string;
  bgColor: string;
}

// Generate mock drawdown history
const generateMockDrawdowns = (): DrawdownPeriod[] => {
  return [
    {
      startDate: '2025-11-01',
      endDate: '2025-11-15',
      duration: 14,
      peakValue: 32000,
      troughValue: 29120,
      drawdownPercent: -9.0,
      recovered: true,
    },
    {
      startDate: '2025-09-15',
      endDate: '2025-10-05',
      duration: 20,
      peakValue: 28500,
      troughValue: 26505,
      drawdownPercent: -7.0,
      recovered: true,
    },
    {
      startDate: '2025-07-20',
      endDate: '2025-08-10',
      duration: 21,
      peakValue: 25000,
      troughValue: 23250,
      drawdownPercent: -7.0,
      recovered: true,
    },
  ];
};

// Calculate risk rating based on metrics
const calculateRiskRating = (metrics: PortfolioMetrics | null): RiskRating => {
  if (!metrics) {
    return {
      level: 'moderate',
      score: 50,
      label: 'Moderado',
      color: 'text-yellow-500',
      bgColor: 'bg-yellow-100 dark:bg-yellow-900/30',
    };
  }

  let score = 50;

  // Volatility impact (higher = more risk)
  if (metrics.volatility > 30) score += 20;
  else if (metrics.volatility > 20) score += 10;
  else if (metrics.volatility < 10) score -= 15;

  // Sharpe ratio impact (higher = less risk)
  if (metrics.sharpeRatio > 2) score -= 20;
  else if (metrics.sharpeRatio > 1) score -= 10;
  else if (metrics.sharpeRatio < 0.5) score += 15;

  // Max drawdown impact
  const absDrawdown = Math.abs(metrics.maxDrawdownPercent);
  if (absDrawdown > 25) score += 20;
  else if (absDrawdown > 15) score += 10;
  else if (absDrawdown < 5) score -= 10;

  // Beta impact
  if (metrics.beta > 1.5) score += 15;
  else if (metrics.beta > 1.2) score += 5;
  else if (metrics.beta < 0.8) score -= 10;

  score = Math.max(0, Math.min(100, score));

  if (score >= 70) {
    return {
      level: 'very-high',
      score,
      label: 'Muy Alto',
      color: 'text-red-600',
      bgColor: 'bg-red-100 dark:bg-red-900/30',
    };
  } else if (score >= 50) {
    return {
      level: 'high',
      score,
      label: 'Alto',
      color: 'text-orange-500',
      bgColor: 'bg-orange-100 dark:bg-orange-900/30',
    };
  } else if (score >= 30) {
    return {
      level: 'moderate',
      score,
      label: 'Moderado',
      color: 'text-yellow-500',
      bgColor: 'bg-yellow-100 dark:bg-yellow-900/30',
    };
  } else {
    return {
      level: 'low',
      score,
      label: 'Bajo',
      color: 'text-green-500',
      bgColor: 'bg-green-100 dark:bg-green-900/30',
    };
  }
};

// Metric Card Component
interface MetricCardProps {
  label: string;
  value: string | number;
  tooltip: string;
  type?: 'positive' | 'negative' | 'neutral' | 'info';
  suffix?: string;
  benchmark?: number;
  benchmarkLabel?: string;
}

const MetricCard: React.FC<MetricCardProps> = ({
  label,
  value,
  tooltip,
  type = 'neutral',
  suffix = '',
  benchmark,
  benchmarkLabel,
}) => {
  const [showTooltip, setShowTooltip] = useState(false);

  const valueColorClass =
    type === 'positive'
      ? 'text-green-500'
      : type === 'negative'
      ? 'text-red-500'
      : type === 'info'
      ? 'text-blue-500'
      : 'text-gray-900 dark:text-white';

  return (
    <div className="p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg relative">
      <div className="flex items-center justify-between mb-1">
        <span className="text-xs text-gray-500 dark:text-gray-400">{label}</span>
        <div
          className="relative"
          onMouseEnter={() => setShowTooltip(true)}
          onMouseLeave={() => setShowTooltip(false)}
        >
          <InformationCircleIcon className="w-4 h-4 text-gray-400 cursor-help" />
          {showTooltip && (
            <div className="absolute bottom-full right-0 mb-2 px-3 py-2 bg-gray-900 text-white text-xs rounded-lg w-48 z-10">
              {tooltip}
            </div>
          )}
        </div>
      </div>
      <p className={`text-xl font-bold ${valueColorClass}`}>
        {typeof value === 'number' ? value.toFixed(2) : value}
        {suffix}
      </p>
      {benchmark !== undefined && (
        <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
          {benchmarkLabel || 'Benchmark'}: {benchmark.toFixed(2)}{suffix}
        </p>
      )}
    </div>
  );
};

export const RiskAnalytics: React.FC<RiskAnalyticsProps> = ({
  portfolioId,
  allocations = [],
  metrics = null,
  compact = false,
}) => {
  const [drawdowns, setDrawdowns] = useState<DrawdownPeriod[]>([]);
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState<'overview' | 'drawdown' | 'details'>('overview');

  // Load drawdown data
  useEffect(() => {
    setDrawdowns(generateMockDrawdowns());
  }, [portfolioId]);

  // Calculate risk rating
  const riskRating = useMemo(() => calculateRiskRating(metrics), [metrics]);

  // Use mock metrics if none provided
  const displayMetrics: PortfolioMetrics = metrics || {
    totalReturn: 2543.67,
    totalReturnPercent: 25.44,
    annualizedReturn: 1850.25,
    annualizedReturnPercent: 18.5,
    volatility: 22.35,
    sharpeRatio: 1.25,
    sortinoRatio: 1.62,
    maxDrawdown: -2856.32,
    maxDrawdownPercent: -9.52,
    maxDrawdownDate: '2025-11-15',
    beta: 1.15,
    alpha: 2.8,
    rSquared: 0.82,
    trackingError: 5.2,
    informationRatio: 0.54,
    calmarRatio: 1.94,
    updatedAt: new Date().toISOString(),
  };

  if (compact) {
    return (
      <div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-red-100 dark:bg-red-900/30 rounded-lg">
              <ShieldExclamationIcon className="w-5 h-5 text-red-600" />
            </div>
            <h3 className="font-bold text-gray-900 dark:text-white">Riesgo</h3>
          </div>
          <div className={`px-2 py-1 rounded-full ${riskRating.bgColor}`}>
            <span className={`text-xs font-medium ${riskRating.color}`}>
              {riskRating.label}
            </span>
          </div>
        </div>

        <div className="grid grid-cols-2 gap-3">
          <div className="text-center p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
            <p className="text-xs text-gray-500 dark:text-gray-400">Sharpe</p>
            <p className={`text-lg font-bold ${
              displayMetrics.sharpeRatio >= 1 ? 'text-green-500' :
              displayMetrics.sharpeRatio >= 0.5 ? 'text-yellow-500' : 'text-red-500'
            }`}>
              {displayMetrics.sharpeRatio.toFixed(2)}
            </p>
          </div>
          <div className="text-center p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
            <p className="text-xs text-gray-500 dark:text-gray-400">Beta</p>
            <p className="text-lg font-bold text-gray-900 dark:text-white">
              {displayMetrics.beta.toFixed(2)}
            </p>
          </div>
          <div className="text-center p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
            <p className="text-xs text-gray-500 dark:text-gray-400">Volatilidad</p>
            <p className="text-lg font-bold text-gray-900 dark:text-white">
              {displayMetrics.volatility.toFixed(1)}%
            </p>
          </div>
          <div className="text-center p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
            <p className="text-xs text-gray-500 dark:text-gray-400">Max DD</p>
            <p className="text-lg font-bold text-red-500">
              {displayMetrics.maxDrawdownPercent.toFixed(1)}%
            </p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg">
      {/* Header */}
      <div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
        <div className="flex items-center gap-3">
          <div className="p-2 bg-red-100 dark:bg-red-900/30 rounded-lg">
            <ShieldExclamationIcon className="w-6 h-6 text-red-600" />
          </div>
          <div>
            <h3 className="font-bold text-gray-900 dark:text-white">Analisis de Riesgo</h3>
            <p className="text-sm text-gray-500 dark:text-gray-400">
              Metricas y evaluacion de riesgo del portfolio
            </p>
          </div>
        </div>

        {/* Risk Rating Badge */}
        <div className={`px-4 py-2 rounded-lg ${riskRating.bgColor}`}>
          <span className="text-xs text-gray-500 dark:text-gray-400">Nivel de Riesgo: </span>
          <span className={`font-bold ${riskRating.color}`}>
            {riskRating.label} ({riskRating.score}/100)
          </span>
        </div>
      </div>

      {/* Tabs */}
      <div className="flex gap-1 p-2 mx-6 mt-4 bg-gray-100 dark:bg-gray-700 rounded-lg">
        <button
          onClick={() => setActiveTab('overview')}
          className={`flex-1 px-3 py-2 text-sm font-medium rounded-md transition-colors ${
            activeTab === 'overview'
              ? 'bg-white dark:bg-gray-600 text-gray-900 dark:text-white shadow-sm'
              : 'text-gray-600 dark:text-gray-400 hover:text-gray-900'
          }`}
        >
          Resumen
        </button>
        <button
          onClick={() => setActiveTab('drawdown')}
          className={`flex-1 px-3 py-2 text-sm font-medium rounded-md transition-colors ${
            activeTab === 'drawdown'
              ? 'bg-white dark:bg-gray-600 text-gray-900 dark:text-white shadow-sm'
              : 'text-gray-600 dark:text-gray-400 hover:text-gray-900'
          }`}
        >
          Drawdown
        </button>
        <button
          onClick={() => setActiveTab('details')}
          className={`flex-1 px-3 py-2 text-sm font-medium rounded-md transition-colors ${
            activeTab === 'details'
              ? 'bg-white dark:bg-gray-600 text-gray-900 dark:text-white shadow-sm'
              : 'text-gray-600 dark:text-gray-400 hover:text-gray-900'
          }`}
        >
          Detalles
        </button>
      </div>

      {/* Content */}
      <div className="p-6">
        {/* Overview Tab */}
        {activeTab === 'overview' && (
          <>
            {/* Risk Score Visualization */}
            <div className="mb-6">
              <h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3">
                Puntuacion de Riesgo
              </h4>
              <div className="relative h-4 bg-gradient-to-r from-green-500 via-yellow-500 to-red-500 rounded-full">
                <div
                  className="absolute top-1/2 transform -translate-y-1/2 -translate-x-1/2 w-6 h-6 bg-white border-2 border-gray-900 rounded-full shadow-lg"
                  style={{ left: `${riskRating.score}%` }}
                />
              </div>
              <div className="flex justify-between text-xs text-gray-500 dark:text-gray-400 mt-2">
                <span>Bajo Riesgo</span>
                <span>Alto Riesgo</span>
              </div>
            </div>

            {/* Key Metrics Grid */}
            <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
              <MetricCard
                label="Sharpe Ratio"
                value={displayMetrics.sharpeRatio}
                tooltip="Retorno en exceso por unidad de riesgo. Mayor a 1 es bueno, mayor a 2 es excelente."
                type={displayMetrics.sharpeRatio >= 1 ? 'positive' : displayMetrics.sharpeRatio >= 0.5 ? 'neutral' : 'negative'}
                benchmark={1.0}
                benchmarkLabel="Objetivo"
              />
              <MetricCard
                label="Beta"
                value={displayMetrics.beta}
                tooltip="Sensibilidad al mercado. Beta 1 = igual que mercado, >1 = mas volatil, <1 = menos volatil."
                type={displayMetrics.beta > 1.3 ? 'negative' : displayMetrics.beta < 0.7 ? 'info' : 'neutral'}
                benchmark={1.0}
                benchmarkLabel="Mercado"
              />
              <MetricCard
                label="Volatilidad Anual"
                value={displayMetrics.volatility}
                suffix="%"
                tooltip="Desviacion estandar anualizada de los retornos. Mide la variabilidad del portfolio."
                type={displayMetrics.volatility > 30 ? 'negative' : displayMetrics.volatility < 15 ? 'positive' : 'neutral'}
              />
              <MetricCard
                label="Max Drawdown"
                value={displayMetrics.maxDrawdownPercent}
                suffix="%"
                tooltip="Maxima caida desde un pico. Menor es mejor."
                type="negative"
              />
            </div>

            {/* Risk-Adjusted Returns */}
            <div className="mb-6">
              <h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3">
                Retornos Ajustados por Riesgo
              </h4>
              <div className="grid md:grid-cols-3 gap-4">
                <MetricCard
                  label="Alpha"
                  value={displayMetrics.alpha}
                  suffix="%"
                  tooltip="Rendimiento en exceso sobre el benchmark. Alpha positivo indica gestion superior."
                  type={displayMetrics.alpha >= 0 ? 'positive' : 'negative'}
                />
                <MetricCard
                  label="Sortino Ratio"
                  value={displayMetrics.sortinoRatio}
                  tooltip="Similar al Sharpe pero solo considera la volatilidad a la baja. Mayor es mejor."
                  type={displayMetrics.sortinoRatio >= 1 ? 'positive' : 'neutral'}
                />
                <MetricCard
                  label="Calmar Ratio"
                  value={displayMetrics.calmarRatio}
                  tooltip="Retorno anualizado dividido por max drawdown. Mayor es mejor."
                  type={displayMetrics.calmarRatio >= 1 ? 'positive' : 'neutral'}
                />
              </div>
            </div>

            {/* Risk Interpretation */}
            <div className={`p-4 rounded-lg border ${
              riskRating.level === 'low' ? 'bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800' :
              riskRating.level === 'moderate' ? 'bg-yellow-50 dark:bg-yellow-900/20 border-yellow-200 dark:border-yellow-800' :
              'bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800'
            }`}>
              <h4 className={`font-medium ${riskRating.color} mb-2`}>
                Interpretacion: Riesgo {riskRating.label}
              </h4>
              <p className="text-sm text-gray-600 dark:text-gray-400">
                {riskRating.level === 'low' && 'Tu portfolio tiene un perfil de riesgo conservador con buena diversificacion y volatilidad controlada.'}
                {riskRating.level === 'moderate' && 'Tu portfolio tiene un nivel de riesgo equilibrado, adecuado para inversores con tolerancia moderada.'}
                {riskRating.level === 'high' && 'Tu portfolio presenta volatilidad elevada. Considera rebalancear para reducir la exposicion al riesgo.'}
                {riskRating.level === 'very-high' && 'Tu portfolio tiene alta exposicion al riesgo. Se recomienda diversificar y reducir posiciones volatiles.'}
              </p>
            </div>
          </>
        )}

        {/* Drawdown Tab */}
        {activeTab === 'drawdown' && (
          <>
            {/* Current Drawdown Status */}
            <div className="mb-6 p-4 bg-red-50 dark:bg-red-900/20 rounded-lg border border-red-200 dark:border-red-800">
              <div className="flex items-center gap-3 mb-3">
                <ArrowTrendingDownIcon className="w-6 h-6 text-red-500" />
                <div>
                  <h4 className="font-bold text-red-700 dark:text-red-300">
                    Max Drawdown: {displayMetrics.maxDrawdownPercent.toFixed(2)}%
                  </h4>
                  <p className="text-sm text-red-600 dark:text-red-400">
                    Registrado el {displayMetrics.maxDrawdownDate ? new Date(displayMetrics.maxDrawdownDate).toLocaleDateString() : 'N/A'}
                  </p>
                </div>
              </div>
              <p className="text-sm text-red-600 dark:text-red-400">
                Perdida maxima: ${Math.abs(displayMetrics.maxDrawdown).toLocaleString(undefined, { minimumFractionDigits: 2 })}
              </p>
            </div>

            {/* Drawdown History */}
            <div className="mb-6">
              <h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3">
                Historial de Drawdowns
              </h4>
              <div className="space-y-3">
                {drawdowns.map((dd, index) => (
                  <div
                    key={index}
                    className="p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg"
                  >
                    <div className="flex items-center justify-between mb-2">
                      <div className="flex items-center gap-2">
                        <span className={`p-1 rounded-full ${dd.recovered ? 'bg-green-100 dark:bg-green-900/30' : 'bg-red-100 dark:bg-red-900/30'}`}>
                          {dd.recovered ? (
                            <ChartBarIcon className="w-4 h-4 text-green-500" />
                          ) : (
                            <ArrowTrendingDownIcon className="w-4 h-4 text-red-500" />
                          )}
                        </span>
                        <span className="font-medium text-gray-900 dark:text-white">
                          {new Date(dd.startDate).toLocaleDateString()} - {new Date(dd.endDate).toLocaleDateString()}
                        </span>
                      </div>
                      <span className={`font-bold ${dd.recovered ? 'text-green-500' : 'text-red-500'}`}>
                        {dd.drawdownPercent.toFixed(1)}%
                      </span>
                    </div>
                    <div className="grid grid-cols-4 gap-4 text-sm">
                      <div>
                        <p className="text-gray-500 dark:text-gray-400">Duracion</p>
                        <p className="font-medium text-gray-900 dark:text-white">{dd.duration} dias</p>
                      </div>
                      <div>
                        <p className="text-gray-500 dark:text-gray-400">Pico</p>
                        <p className="font-medium text-gray-900 dark:text-white">${dd.peakValue.toLocaleString()}</p>
                      </div>
                      <div>
                        <p className="text-gray-500 dark:text-gray-400">Valle</p>
                        <p className="font-medium text-gray-900 dark:text-white">${dd.troughValue.toLocaleString()}</p>
                      </div>
                      <div>
                        <p className="text-gray-500 dark:text-gray-400">Estado</p>
                        <p className={`font-medium ${dd.recovered ? 'text-green-500' : 'text-red-500'}`}>
                          {dd.recovered ? 'Recuperado' : 'En progreso'}
                        </p>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>

            {/* Drawdown Guidelines */}
            <div className="p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-800">
              <div className="flex items-start gap-3">
                <InformationCircleIcon className="w-5 h-5 text-blue-500 flex-shrink-0 mt-0.5" />
                <div>
                  <h4 className="font-medium text-blue-800 dark:text-blue-200">
                    Guia de Drawdown
                  </h4>
                  <ul className="mt-2 text-sm text-blue-700 dark:text-blue-300 space-y-1">
                    <li>• {'<'}5%: Normal, parte de la volatilidad del mercado</li>
                    <li>• 5-10%: Moderado, considerar revisar posiciones</li>
                    <li>• 10-20%: Significativo, evaluar estrategia de riesgo</li>
                    <li>• {'>'}20%: Severo, tomar acciones correctivas</li>
                  </ul>
                </div>
              </div>
            </div>
          </>
        )}

        {/* Details Tab */}
        {activeTab === 'details' && (
          <>
            {/* All Metrics */}
            <div className="grid md:grid-cols-2 gap-4">
              {/* Returns Section */}
              <div className="p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
                <h4 className="font-semibold text-gray-700 dark:text-gray-300 mb-3">
                  Retornos
                </h4>
                <div className="space-y-2 text-sm">
                  <div className="flex justify-between">
                    <span className="text-gray-500 dark:text-gray-400">Retorno Total</span>
                    <span className={`font-medium ${displayMetrics.totalReturnPercent >= 0 ? 'text-green-500' : 'text-red-500'}`}>
                      {displayMetrics.totalReturnPercent >= 0 ? '+' : ''}{displayMetrics.totalReturnPercent.toFixed(2)}%
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-500 dark:text-gray-400">Retorno Anualizado</span>
                    <span className={`font-medium ${displayMetrics.annualizedReturnPercent >= 0 ? 'text-green-500' : 'text-red-500'}`}>
                      {displayMetrics.annualizedReturnPercent >= 0 ? '+' : ''}{displayMetrics.annualizedReturnPercent.toFixed(2)}%
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-500 dark:text-gray-400">Alpha</span>
                    <span className={`font-medium ${displayMetrics.alpha >= 0 ? 'text-green-500' : 'text-red-500'}`}>
                      {displayMetrics.alpha >= 0 ? '+' : ''}{displayMetrics.alpha.toFixed(2)}%
                    </span>
                  </div>
                </div>
              </div>

              {/* Risk Section */}
              <div className="p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
                <h4 className="font-semibold text-gray-700 dark:text-gray-300 mb-3">
                  Metricas de Riesgo
                </h4>
                <div className="space-y-2 text-sm">
                  <div className="flex justify-between">
                    <span className="text-gray-500 dark:text-gray-400">Volatilidad</span>
                    <span className="font-medium text-gray-900 dark:text-white">
                      {displayMetrics.volatility.toFixed(2)}%
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-500 dark:text-gray-400">Beta</span>
                    <span className="font-medium text-gray-900 dark:text-white">
                      {displayMetrics.beta.toFixed(2)}
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-500 dark:text-gray-400">Max Drawdown</span>
                    <span className="font-medium text-red-500">
                      {displayMetrics.maxDrawdownPercent.toFixed(2)}%
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-500 dark:text-gray-400">Tracking Error</span>
                    <span className="font-medium text-gray-900 dark:text-white">
                      {displayMetrics.trackingError.toFixed(2)}%
                    </span>
                  </div>
                </div>
              </div>

              {/* Risk-Adjusted Section */}
              <div className="p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
                <h4 className="font-semibold text-gray-700 dark:text-gray-300 mb-3">
                  Ratios Ajustados
                </h4>
                <div className="space-y-2 text-sm">
                  <div className="flex justify-between">
                    <span className="text-gray-500 dark:text-gray-400">Sharpe Ratio</span>
                    <span className={`font-medium ${displayMetrics.sharpeRatio >= 1 ? 'text-green-500' : 'text-gray-900 dark:text-white'}`}>
                      {displayMetrics.sharpeRatio.toFixed(2)}
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-500 dark:text-gray-400">Sortino Ratio</span>
                    <span className={`font-medium ${displayMetrics.sortinoRatio >= 1 ? 'text-green-500' : 'text-gray-900 dark:text-white'}`}>
                      {displayMetrics.sortinoRatio.toFixed(2)}
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-500 dark:text-gray-400">Information Ratio</span>
                    <span className="font-medium text-gray-900 dark:text-white">
                      {displayMetrics.informationRatio.toFixed(2)}
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-500 dark:text-gray-400">Calmar Ratio</span>
                    <span className={`font-medium ${displayMetrics.calmarRatio >= 1 ? 'text-green-500' : 'text-gray-900 dark:text-white'}`}>
                      {displayMetrics.calmarRatio.toFixed(2)}
                    </span>
                  </div>
                </div>
              </div>

              {/* Correlation Section */}
              <div className="p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
                <h4 className="font-semibold text-gray-700 dark:text-gray-300 mb-3">
                  Correlacion con Mercado
                </h4>
                <div className="space-y-2 text-sm">
                  <div className="flex justify-between">
                    <span className="text-gray-500 dark:text-gray-400">R-Squared</span>
                    <span className="font-medium text-gray-900 dark:text-white">
                      {(displayMetrics.rSquared * 100).toFixed(0)}%
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-500 dark:text-gray-400">Beta</span>
                    <span className="font-medium text-gray-900 dark:text-white">
                      {displayMetrics.beta.toFixed(2)}
                    </span>
                  </div>
                  <div className="mt-2 text-xs text-gray-500 dark:text-gray-400">
                    R-squared de {(displayMetrics.rSquared * 100).toFixed(0)}% indica que{' '}
                    {displayMetrics.rSquared >= 0.7 ? 'alta' : displayMetrics.rSquared >= 0.4 ? 'moderada' : 'baja'}{' '}
                    correlacion con el mercado de referencia.
                  </div>
                </div>
              </div>
            </div>

            {/* Last Update */}
            <div className="mt-4 text-xs text-gray-500 dark:text-gray-400 text-right">
              Ultima actualizacion: {new Date(displayMetrics.updatedAt).toLocaleString()}
            </div>
          </>
        )}
      </div>
    </div>
  );
};

export default RiskAnalytics;
