/**
 * Performance Metrics Card Component
 * Displays detailed portfolio performance metrics including
 * returns, volatility, Sharpe ratio, and drawdown
 */

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

interface PerformanceMetricsCardProps {
  portfolioId: string;
  compact?: boolean;
}

interface MetricItemProps {
  label: string;
  value: string | number;
  tooltip?: string;
  type?: 'positive' | 'negative' | 'neutral';
  suffix?: string;
}

const MetricItem: React.FC<MetricItemProps> = ({
  label,
  value,
  tooltip,
  type = 'neutral',
  suffix = '',
}) => {
  const colorClass =
    type === 'positive'
      ? 'text-green-500'
      : type === 'negative'
      ? 'text-red-500'
      : 'text-gray-900 dark:text-white';

  return (
    <div className="flex justify-between items-center py-2">
      <div className="flex items-center gap-1">
        <span className="text-sm text-gray-500 dark:text-gray-400">{label}</span>
        {tooltip && (
          <div className="group relative">
            <InformationCircleIcon className="w-4 h-4 text-gray-400 cursor-help" />
            <div className="absolute bottom-full left-1/2 -translate-x-1/2 mb-2 px-3 py-2 bg-gray-900 text-white text-xs rounded-lg opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap z-10">
              {tooltip}
            </div>
          </div>
        )}
      </div>
      <span className={`font-medium ${colorClass}`}>
        {typeof value === 'number' ? value.toFixed(2) : value}
        {suffix}
      </span>
    </div>
  );
};

export const PerformanceMetricsCard: React.FC<PerformanceMetricsCardProps> = ({
  portfolioId,
  compact = false,
}) => {
  const [metrics, setMetrics] = useState<PortfolioMetrics | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    loadMetrics();
  }, [portfolioId]);

  const loadMetrics = async () => {
    try {
      setLoading(true);
      setError(null);
      const data = await getPortfolioMetrics(portfolioId);
      setMetrics(data);
    } catch (err) {
      console.error('Error loading metrics:', err);
      setError(err instanceof Error ? err.message : 'Failed to load metrics');
      // Use mock data for demo
      setMetrics(generateMockMetrics());
    } finally {
      setLoading(false);
    }
  };

  const generateMockMetrics = (): PortfolioMetrics => ({
    totalReturn: 2543.67,
    totalReturnPercent: 25.44,
    annualizedReturn: 1850.25,
    annualizedReturnPercent: 18.5,
    volatility: 12.35,
    sharpeRatio: 1.45,
    sortinoRatio: 1.82,
    maxDrawdown: -856.32,
    maxDrawdownPercent: -8.56,
    maxDrawdownDate: '2025-11-15',
    beta: 0.85,
    alpha: 3.2,
    rSquared: 0.78,
    trackingError: 4.5,
    informationRatio: 0.71,
    calmarRatio: 2.16,
    updatedAt: new Date().toISOString(),
  });

  if (loading) {
    return (
      <div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
        <div className="flex items-center gap-3 mb-4">
          <div className="p-2 bg-blue-100 dark:bg-blue-900/30 rounded-lg">
            <ChartBarIcon className="w-5 h-5 text-blue-600" />
          </div>
          <h3 className="font-bold text-gray-900 dark:text-white">Metricas de Rendimiento</h3>
        </div>
        <div className="flex items-center justify-center py-8">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
        </div>
      </div>
    );
  }

  if (!metrics) {
    return (
      <div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
        <div className="text-center py-4">
          <ExclamationTriangleIcon className="w-8 h-8 text-yellow-500 mx-auto mb-2" />
          <p className="text-gray-500 dark:text-gray-400">
            {error || 'No hay metricas disponibles'}
          </p>
        </div>
      </div>
    );
  }

  const isPositiveReturn = metrics.totalReturnPercent >= 0;

  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-blue-100 dark:bg-blue-900/30 rounded-lg">
              <ChartBarIcon className="w-5 h-5 text-blue-600" />
            </div>
            <h3 className="font-bold text-gray-900 dark:text-white">Metricas</h3>
          </div>
        </div>
        <div className="grid grid-cols-2 gap-4">
          <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 ${metrics.sharpeRatio >= 1 ? 'text-green-500' : metrics.sharpeRatio >= 0 ? 'text-yellow-500' : 'text-red-500'}`}>
              {metrics.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">Volatilidad</p>
            <p className="text-lg font-bold text-gray-900 dark:text-white">
              {metrics.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">
              {metrics.maxDrawdownPercent.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">Retorno Anual</p>
            <p className={`text-lg font-bold ${metrics.annualizedReturnPercent >= 0 ? 'text-green-500' : 'text-red-500'}`}>
              {metrics.annualizedReturnPercent >= 0 ? '+' : ''}{metrics.annualizedReturnPercent.toFixed(1)}%
            </p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-3">
          <div className="p-2 bg-blue-100 dark:bg-blue-900/30 rounded-lg">
            <ChartBarIcon className="w-5 h-5 text-blue-600" />
          </div>
          <div>
            <h3 className="font-bold text-gray-900 dark:text-white">Metricas de Rendimiento</h3>
            <p className="text-xs text-gray-500 dark:text-gray-400">
              Actualizado: {new Date(metrics.updatedAt).toLocaleString()}
            </p>
          </div>
        </div>
      </div>

      {/* Main Return Display */}
      <div className="mb-6 p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
        <div className="flex items-center justify-between">
          <div>
            <p className="text-sm text-gray-500 dark:text-gray-400">Retorno Total</p>
            <div className="flex items-center gap-2">
              {isPositiveReturn ? (
                <ArrowTrendingUpIcon className="w-6 h-6 text-green-500" />
              ) : (
                <ArrowTrendingDownIcon className="w-6 h-6 text-red-500" />
              )}
              <span className={`text-2xl font-bold ${isPositiveReturn ? 'text-green-500' : 'text-red-500'}`}>
                {isPositiveReturn ? '+' : ''}${Math.abs(metrics.totalReturn).toLocaleString(undefined, { minimumFractionDigits: 2 })}
              </span>
            </div>
          </div>
          <div className="text-right">
            <p className="text-sm text-gray-500 dark:text-gray-400">Porcentaje</p>
            <span className={`text-2xl font-bold ${isPositiveReturn ? 'text-green-500' : 'text-red-500'}`}>
              {isPositiveReturn ? '+' : ''}{metrics.totalReturnPercent.toFixed(2)}%
            </span>
          </div>
        </div>
      </div>

      {/* Returns Section */}
      <div className="mb-4">
        <h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
          Retornos
        </h4>
        <div className="space-y-1 border-b border-gray-200 dark:border-gray-700 pb-4">
          <MetricItem
            label="Retorno Anualizado"
            value={`${metrics.annualizedReturnPercent >= 0 ? '+' : ''}${metrics.annualizedReturnPercent.toFixed(2)}`}
            suffix="%"
            type={metrics.annualizedReturnPercent >= 0 ? 'positive' : 'negative'}
            tooltip="Retorno proyectado anual basado en el rendimiento actual"
          />
          <MetricItem
            label="Alpha"
            value={`${metrics.alpha >= 0 ? '+' : ''}${metrics.alpha.toFixed(2)}`}
            suffix="%"
            type={metrics.alpha >= 0 ? 'positive' : 'negative'}
            tooltip="Rendimiento en exceso sobre el benchmark"
          />
        </div>
      </div>

      {/* Risk Metrics Section */}
      <div className="mb-4">
        <h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
          Metricas de Riesgo
        </h4>
        <div className="space-y-1 border-b border-gray-200 dark:border-gray-700 pb-4">
          <MetricItem
            label="Volatilidad"
            value={metrics.volatility}
            suffix="%"
            tooltip="Desviacion estandar anualizada de los retornos"
          />
          <MetricItem
            label="Beta"
            value={metrics.beta}
            tooltip="Sensibilidad al mercado (1 = igual que el mercado)"
          />
          <MetricItem
            label="R-Squared"
            value={(metrics.rSquared * 100).toFixed(0)}
            suffix="%"
            tooltip="Porcentaje de variacion explicado por el benchmark"
          />
          <MetricItem
            label="Tracking Error"
            value={metrics.trackingError}
            suffix="%"
            tooltip="Desviacion de los retornos respecto al benchmark"
          />
        </div>
      </div>

      {/* Risk-Adjusted Returns Section */}
      <div className="mb-4">
        <h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
          Retornos Ajustados por Riesgo
        </h4>
        <div className="space-y-1 border-b border-gray-200 dark:border-gray-700 pb-4">
          <MetricItem
            label="Sharpe Ratio"
            value={metrics.sharpeRatio}
            type={metrics.sharpeRatio >= 1 ? 'positive' : metrics.sharpeRatio >= 0 ? 'neutral' : 'negative'}
            tooltip="Retorno en exceso por unidad de riesgo (>1 es bueno)"
          />
          <MetricItem
            label="Sortino Ratio"
            value={metrics.sortinoRatio}
            type={metrics.sortinoRatio >= 1 ? 'positive' : metrics.sortinoRatio >= 0 ? 'neutral' : 'negative'}
            tooltip="Como Sharpe pero solo considera riesgo a la baja"
          />
          <MetricItem
            label="Information Ratio"
            value={metrics.informationRatio}
            type={metrics.informationRatio >= 0.5 ? 'positive' : 'neutral'}
            tooltip="Alpha dividido por tracking error"
          />
          <MetricItem
            label="Calmar Ratio"
            value={metrics.calmarRatio}
            type={metrics.calmarRatio >= 1 ? 'positive' : 'neutral'}
            tooltip="Retorno anualizado dividido por max drawdown"
          />
        </div>
      </div>

      {/* Drawdown Section */}
      <div>
        <h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
          Drawdown
        </h4>
        <div className="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 justify-between mb-2">
            <div className="flex items-center gap-2">
              <ExclamationTriangleIcon className="w-5 h-5 text-red-500" />
              <span className="text-sm text-gray-600 dark:text-gray-400">Max Drawdown</span>
            </div>
            <span className="text-lg font-bold text-red-500">
              {metrics.maxDrawdownPercent.toFixed(2)}%
            </span>
          </div>
          <div className="flex justify-between text-sm">
            <span className="text-gray-500 dark:text-gray-400">Monto</span>
            <span className="text-red-500">
              ${Math.abs(metrics.maxDrawdown).toLocaleString(undefined, { minimumFractionDigits: 2 })}
            </span>
          </div>
          {metrics.maxDrawdownDate && (
            <div className="flex justify-between text-sm mt-1">
              <span className="text-gray-500 dark:text-gray-400">Fecha</span>
              <span className="text-gray-600 dark:text-gray-300">
                {new Date(metrics.maxDrawdownDate).toLocaleDateString()}
              </span>
            </div>
          )}
        </div>
      </div>

      {/* Quality Indicators */}
      <div className="mt-4 pt-4 border-t border-gray-200 dark:border-gray-700">
        <div className="flex items-center gap-4 text-xs text-gray-500 dark:text-gray-400">
          <div className="flex items-center gap-1">
            <span className={`w-2 h-2 rounded-full ${metrics.sharpeRatio >= 1 ? 'bg-green-500' : metrics.sharpeRatio >= 0 ? 'bg-yellow-500' : 'bg-red-500'}`}></span>
            Sharpe: {metrics.sharpeRatio >= 1 ? 'Bueno' : metrics.sharpeRatio >= 0 ? 'Aceptable' : 'Bajo'}
          </div>
          <div className="flex items-center gap-1">
            <span className={`w-2 h-2 rounded-full ${Math.abs(metrics.maxDrawdownPercent) <= 10 ? 'bg-green-500' : Math.abs(metrics.maxDrawdownPercent) <= 20 ? 'bg-yellow-500' : 'bg-red-500'}`}></span>
            Drawdown: {Math.abs(metrics.maxDrawdownPercent) <= 10 ? 'Bajo' : Math.abs(metrics.maxDrawdownPercent) <= 20 ? 'Moderado' : 'Alto'}
          </div>
        </div>
      </div>
    </div>
  );
};

export default PerformanceMetricsCard;
