/**
 * Allocation Optimizer Component
 * Portfolio optimization using Modern Portfolio Theory
 * with efficient frontier visualization and allocation suggestions
 */

import React, { useState, useMemo, useCallback } from 'react';
import {
  SparklesIcon,
  PlayIcon,
  ArrowPathIcon,
  AdjustmentsHorizontalIcon,
  ChartBarIcon,
  ArrowTrendingUpIcon,
  ExclamationTriangleIcon,
  CheckCircleIcon,
  InformationCircleIcon,
} from '@heroicons/react/24/solid';
import {
  ScatterChart,
  Scatter,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  ReferenceLine,
  Cell,
} from 'recharts';
import type { PortfolioAllocation } from '../../../services/portfolio.service';

// ============================================================================
// Types
// ============================================================================

interface AllocationOptimizerProps {
  portfolioId: string;
  allocations: PortfolioAllocation[];
  totalValue: number;
  compact?: boolean;
}

interface OptimizationConstraints {
  riskTolerance: number;
  minWeight: number;
  maxWeight: number;
  includeStablecoins: boolean;
}

interface OptimalAllocation {
  asset: string;
  currentWeight: number;
  optimalWeight: number;
  difference: number;
  expectedReturn: number;
  volatility: number;
}

interface EfficientFrontierPoint {
  risk: number;
  return: number;
  sharpeRatio: number;
  isOptimal?: boolean;
  isCurrent?: boolean;
}

interface OptimizationResult {
  allocations: OptimalAllocation[];
  expectedReturn: number;
  expectedVolatility: number;
  sharpeRatio: number;
  currentReturn: number;
  currentVolatility: number;
  currentSharpe: number;
}

// ============================================================================
// Mock Data and Calculations
// ============================================================================

const ASSET_METRICS: Record<string, { expectedReturn: number; volatility: number }> = {
  BTC: { expectedReturn: 0.35, volatility: 0.65 },
  ETH: { expectedReturn: 0.40, volatility: 0.75 },
  SOL: { expectedReturn: 0.55, volatility: 0.90 },
  LINK: { expectedReturn: 0.30, volatility: 0.70 },
  AVAX: { expectedReturn: 0.45, volatility: 0.85 },
  ADA: { expectedReturn: 0.25, volatility: 0.80 },
  DOT: { expectedReturn: 0.30, volatility: 0.75 },
  MATIC: { expectedReturn: 0.35, volatility: 0.80 },
  UNI: { expectedReturn: 0.28, volatility: 0.72 },
  USDT: { expectedReturn: 0.05, volatility: 0.01 },
  USDC: { expectedReturn: 0.05, volatility: 0.01 },
};

const DEFAULT_METRICS = { expectedReturn: 0.20, volatility: 0.50 };

function getAssetMetrics(asset: string) {
  return ASSET_METRICS[asset] || DEFAULT_METRICS;
}

function runOptimization(
  allocations: PortfolioAllocation[],
  constraints: OptimizationConstraints
): OptimizationResult {
  const { riskTolerance, minWeight, maxWeight, includeStablecoins } = constraints;
  const riskFactor = riskTolerance / 100;

  // Filter assets
  const stablecoins = ['USDT', 'USDC', 'BUSD', 'DAI'];
  const filteredAllocations = includeStablecoins
    ? allocations
    : allocations.filter((a) => !stablecoins.includes(a.asset));

  // Score each asset based on risk-adjusted returns
  const scoredAssets = filteredAllocations.map((alloc) => {
    const metrics = getAssetMetrics(alloc.asset);
    // Higher risk tolerance favors higher returns, lower risk tolerance favors lower volatility
    const score =
      metrics.expectedReturn * (0.3 + riskFactor * 0.7) -
      metrics.volatility * (1 - riskFactor) * 0.4;
    return {
      asset: alloc.asset,
      currentWeight: alloc.currentPercent / 100,
      metrics,
      score: Math.max(0, score),
    };
  });

  // Calculate optimal weights
  const totalScore = scoredAssets.reduce((sum, a) => sum + a.score, 0);
  let optimalAllocations: OptimalAllocation[] = scoredAssets.map((asset) => {
    const rawWeight = totalScore > 0 ? asset.score / totalScore : 1 / scoredAssets.length;
    const optimalWeight = Math.max(minWeight, Math.min(maxWeight, rawWeight));
    return {
      asset: asset.asset,
      currentWeight: asset.currentWeight,
      optimalWeight,
      difference: optimalWeight - asset.currentWeight,
      expectedReturn: asset.metrics.expectedReturn,
      volatility: asset.metrics.volatility,
    };
  });

  // Normalize weights
  const totalWeight = optimalAllocations.reduce((sum, a) => sum + a.optimalWeight, 0);
  optimalAllocations = optimalAllocations.map((a) => ({
    ...a,
    optimalWeight: a.optimalWeight / totalWeight,
    difference: a.optimalWeight / totalWeight - a.currentWeight,
  }));

  // Calculate portfolio metrics
  const expectedReturn = optimalAllocations.reduce(
    (sum, a) => sum + a.optimalWeight * a.expectedReturn,
    0
  );
  const expectedVolatility = Math.sqrt(
    optimalAllocations.reduce(
      (sum, a) => sum + Math.pow(a.optimalWeight * a.volatility, 2),
      0
    ) * 0.7 // Simplified correlation adjustment
  );

  const currentReturn = optimalAllocations.reduce(
    (sum, a) => sum + a.currentWeight * a.expectedReturn,
    0
  );
  const currentVolatility = Math.sqrt(
    optimalAllocations.reduce(
      (sum, a) => sum + Math.pow(a.currentWeight * a.volatility, 2),
      0
    ) * 0.7
  );

  const riskFreeRate = 0.05;
  const sharpeRatio = expectedVolatility > 0
    ? (expectedReturn - riskFreeRate) / expectedVolatility
    : 0;
  const currentSharpe = currentVolatility > 0
    ? (currentReturn - riskFreeRate) / currentVolatility
    : 0;

  return {
    allocations: optimalAllocations.sort((a, b) => b.optimalWeight - a.optimalWeight),
    expectedReturn,
    expectedVolatility,
    sharpeRatio,
    currentReturn,
    currentVolatility,
    currentSharpe,
  };
}

function generateEfficientFrontier(
  result: OptimizationResult
): EfficientFrontierPoint[] {
  const points: EfficientFrontierPoint[] = [];
  const riskFreeRate = 0.05;

  // Generate frontier curve
  for (let i = 0; i <= 20; i++) {
    const risk = 0.05 + (i / 20) * 0.55; // 5% to 60% volatility
    // Simplified efficient frontier formula
    const returnValue = riskFreeRate + risk * 0.45 + Math.pow(risk, 0.8) * 0.1;
    points.push({
      risk: risk * 100,
      return: returnValue * 100,
      sharpeRatio: (returnValue - riskFreeRate) / risk,
    });
  }

  // Add current portfolio point
  points.push({
    risk: result.currentVolatility * 100,
    return: result.currentReturn * 100,
    sharpeRatio: result.currentSharpe,
    isCurrent: true,
  });

  // Add optimal portfolio point
  points.push({
    risk: result.expectedVolatility * 100,
    return: result.expectedReturn * 100,
    sharpeRatio: result.sharpeRatio,
    isOptimal: true,
  });

  return points;
}

// ============================================================================
// Subcomponents
// ============================================================================

interface AllocationComparisonBarProps {
  asset: string;
  current: number;
  optimal: number;
  color: string;
}

const AllocationComparisonBar: React.FC<AllocationComparisonBarProps> = ({
  asset,
  current,
  optimal,
  color,
}) => {
  const diff = optimal - current;
  const maxPercent = Math.max(current, optimal, 30);

  return (
    <div className="space-y-1">
      <div className="flex items-center justify-between text-sm">
        <span className="font-medium text-gray-900 dark:text-white">{asset}</span>
        <div className="flex items-center gap-2">
          <span className="text-gray-500 dark:text-gray-400">
            {(current * 100).toFixed(1)}% / {(optimal * 100).toFixed(1)}%
          </span>
          <span
            className={`text-xs font-medium px-1.5 py-0.5 rounded ${
              Math.abs(diff) < 0.02
                ? 'bg-gray-100 dark:bg-gray-700 text-gray-600'
                : diff > 0
                ? 'bg-green-100 dark:bg-green-900/30 text-green-600'
                : 'bg-red-100 dark:bg-red-900/30 text-red-600'
            }`}
          >
            {diff > 0 ? '+' : ''}{(diff * 100).toFixed(1)}%
          </span>
        </div>
      </div>
      <div className="relative h-3 bg-gray-100 dark:bg-gray-700 rounded-full overflow-hidden">
        {/* Current bar */}
        <div
          className="absolute top-0 left-0 h-full rounded-full opacity-50"
          style={{
            width: `${(current / maxPercent) * 100}%`,
            backgroundColor: color,
          }}
        />
        {/* Optimal bar (outlined) */}
        <div
          className="absolute top-0 left-0 h-full rounded-full border-2"
          style={{
            width: `${(optimal / maxPercent) * 100}%`,
            borderColor: color,
          }}
        />
      </div>
    </div>
  );
};

const ASSET_COLORS: Record<string, string> = {
  BTC: '#F7931A',
  ETH: '#627EEA',
  SOL: '#9945FF',
  LINK: '#2A5ADA',
  AVAX: '#E84142',
  ADA: '#0033AD',
  DOT: '#E6007A',
  MATIC: '#8247E5',
  UNI: '#FF007A',
  USDT: '#26A17B',
  USDC: '#2775CA',
};

// ============================================================================
// Main Component
// ============================================================================

export const AllocationOptimizer: React.FC<AllocationOptimizerProps> = ({
  portfolioId,
  allocations,
  totalValue,
  compact = false,
}) => {
  const [constraints, setConstraints] = useState<OptimizationConstraints>({
    riskTolerance: 50,
    minWeight: 0.02,
    maxWeight: 0.40,
    includeStablecoins: true,
  });
  const [isOptimizing, setIsOptimizing] = useState(false);
  const [result, setResult] = useState<OptimizationResult | null>(null);
  const [showSettings, setShowSettings] = useState(false);

  // Run optimization
  const handleOptimize = useCallback(() => {
    setIsOptimizing(true);
    // Simulate async operation
    setTimeout(() => {
      const optimizationResult = runOptimization(allocations, constraints);
      setResult(optimizationResult);
      setIsOptimizing(false);
    }, 800);
  }, [allocations, constraints]);

  // Generate efficient frontier data
  const efficientFrontier = useMemo(() => {
    if (!result) return [];
    return generateEfficientFrontier(result);
  }, [result]);

  // Improvement metrics
  const improvements = useMemo(() => {
    if (!result) return null;
    return {
      returnImprovement: result.expectedReturn - result.currentReturn,
      riskReduction: result.currentVolatility - result.expectedVolatility,
      sharpeImprovement: result.sharpeRatio - result.currentSharpe,
    };
  }, [result]);

  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-amber-100 dark:bg-amber-900/30 rounded-lg">
              <SparklesIcon className="w-5 h-5 text-amber-600" />
            </div>
            <h3 className="font-bold text-gray-900 dark:text-white">Optimizador</h3>
          </div>
          <button
            onClick={handleOptimize}
            disabled={isOptimizing}
            className="px-3 py-1.5 bg-amber-600 hover:bg-amber-700 disabled:bg-amber-400 text-white text-sm font-medium rounded-lg transition-colors flex items-center gap-1"
          >
            {isOptimizing ? (
              <ArrowPathIcon className="w-4 h-4 animate-spin" />
            ) : (
              <PlayIcon className="w-4 h-4" />
            )}
            Optimizar
          </button>
        </div>

        {result ? (
          <div className="space-y-3">
            <div className="grid grid-cols-2 gap-3">
              <div className="p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg text-center">
                <p className="text-xs text-gray-500 dark:text-gray-400">Sharpe Actual</p>
                <p className="text-lg font-bold text-gray-900 dark:text-white">
                  {result.currentSharpe.toFixed(2)}
                </p>
              </div>
              <div className="p-3 bg-amber-50 dark:bg-amber-900/20 rounded-lg text-center">
                <p className="text-xs text-amber-600">Sharpe Optimo</p>
                <p className="text-lg font-bold text-amber-600">
                  {result.sharpeRatio.toFixed(2)}
                </p>
              </div>
            </div>
            {improvements && improvements.sharpeImprovement > 0 && (
              <div className="flex items-center gap-2 text-sm text-green-600 dark:text-green-400">
                <CheckCircleIcon className="w-4 h-4" />
                <span>+{(improvements.sharpeImprovement * 100).toFixed(0)}% mejora potencial</span>
              </div>
            )}
          </div>
        ) : (
          <div className="text-center py-4">
            <p className="text-sm text-gray-500 dark:text-gray-400">
              Ejecuta el optimizador para ver sugerencias
            </p>
          </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-amber-100 dark:bg-amber-900/30 rounded-lg">
            <SparklesIcon className="w-6 h-6 text-amber-600" />
          </div>
          <div>
            <h3 className="font-bold text-gray-900 dark:text-white">
              Optimizador de Allocacion
            </h3>
            <p className="text-sm text-gray-500 dark:text-gray-400">
              Teoria Moderna de Portafolios (MPT)
            </p>
          </div>
        </div>
        <div className="flex gap-2">
          <button
            onClick={() => setShowSettings(!showSettings)}
            className={`p-2 rounded-lg transition-colors ${
              showSettings
                ? 'bg-amber-100 dark:bg-amber-900/30 text-amber-600'
                : 'bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400 hover:bg-gray-200 dark:hover:bg-gray-600'
            }`}
          >
            <AdjustmentsHorizontalIcon className="w-5 h-5" />
          </button>
          <button
            onClick={handleOptimize}
            disabled={isOptimizing}
            className="px-4 py-2 bg-amber-600 hover:bg-amber-700 disabled:bg-amber-400 text-white font-medium rounded-lg transition-colors flex items-center gap-2"
          >
            {isOptimizing ? (
              <>
                <ArrowPathIcon className="w-5 h-5 animate-spin" />
                Optimizando...
              </>
            ) : (
              <>
                <PlayIcon className="w-5 h-5" />
                Optimizar
              </>
            )}
          </button>
        </div>
      </div>

      {/* Settings Panel */}
      {showSettings && (
        <div className="p-6 bg-gray-50 dark:bg-gray-700/50 border-b border-gray-200 dark:border-gray-700">
          <h4 className="font-medium text-gray-900 dark:text-white mb-4">
            Restricciones de Optimizacion
          </h4>
          <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-4">
            {/* Risk Tolerance */}
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                Tolerancia al Riesgo: {constraints.riskTolerance}%
              </label>
              <input
                type="range"
                min="0"
                max="100"
                value={constraints.riskTolerance}
                onChange={(e) =>
                  setConstraints({ ...constraints, riskTolerance: Number(e.target.value) })
                }
                className="w-full"
              />
              <div className="flex justify-between text-xs text-gray-500 mt-1">
                <span>Conservador</span>
                <span>Agresivo</span>
              </div>
            </div>

            {/* Min Weight */}
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                Peso Minimo: {(constraints.minWeight * 100).toFixed(0)}%
              </label>
              <input
                type="range"
                min="0"
                max="20"
                value={constraints.minWeight * 100}
                onChange={(e) =>
                  setConstraints({ ...constraints, minWeight: Number(e.target.value) / 100 })
                }
                className="w-full"
              />
            </div>

            {/* Max Weight */}
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                Peso Maximo: {(constraints.maxWeight * 100).toFixed(0)}%
              </label>
              <input
                type="range"
                min="20"
                max="100"
                value={constraints.maxWeight * 100}
                onChange={(e) =>
                  setConstraints({ ...constraints, maxWeight: Number(e.target.value) / 100 })
                }
                className="w-full"
              />
            </div>

            {/* Include Stablecoins */}
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                Incluir Stablecoins
              </label>
              <button
                onClick={() =>
                  setConstraints({ ...constraints, includeStablecoins: !constraints.includeStablecoins })
                }
                className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
                  constraints.includeStablecoins ? 'bg-amber-600' : 'bg-gray-200 dark:bg-gray-600'
                }`}
              >
                <span
                  className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                    constraints.includeStablecoins ? 'translate-x-6' : 'translate-x-1'
                  }`}
                />
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Content */}
      <div className="p-6">
        {result ? (
          <>
            {/* Improvement Summary */}
            {improvements && (
              <div className="grid md:grid-cols-3 gap-4 mb-6">
                <div className={`p-4 rounded-lg border ${
                  improvements.returnImprovement > 0
                    ? 'bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800'
                    : 'bg-gray-50 dark:bg-gray-700/50 border-gray-200 dark:border-gray-600'
                }`}>
                  <div className="flex items-center gap-2 mb-1">
                    <ArrowTrendingUpIcon className={`w-5 h-5 ${
                      improvements.returnImprovement > 0 ? 'text-green-500' : 'text-gray-400'
                    }`} />
                    <span className="text-sm font-medium text-gray-700 dark:text-gray-300">
                      Retorno Esperado
                    </span>
                  </div>
                  <p className="text-2xl font-bold text-gray-900 dark:text-white">
                    {(result.expectedReturn * 100).toFixed(1)}%
                  </p>
                  {improvements.returnImprovement > 0 && (
                    <p className="text-xs text-green-600 mt-1">
                      +{(improvements.returnImprovement * 100).toFixed(1)}% vs actual
                    </p>
                  )}
                </div>

                <div className={`p-4 rounded-lg border ${
                  improvements.riskReduction > 0
                    ? 'bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800'
                    : 'bg-gray-50 dark:bg-gray-700/50 border-gray-200 dark:border-gray-600'
                }`}>
                  <div className="flex items-center gap-2 mb-1">
                    <ExclamationTriangleIcon className={`w-5 h-5 ${
                      improvements.riskReduction > 0 ? 'text-blue-500' : 'text-gray-400'
                    }`} />
                    <span className="text-sm font-medium text-gray-700 dark:text-gray-300">
                      Volatilidad
                    </span>
                  </div>
                  <p className="text-2xl font-bold text-gray-900 dark:text-white">
                    {(result.expectedVolatility * 100).toFixed(1)}%
                  </p>
                  {improvements.riskReduction > 0 && (
                    <p className="text-xs text-blue-600 mt-1">
                      -{(improvements.riskReduction * 100).toFixed(1)}% vs actual
                    </p>
                  )}
                </div>

                <div className={`p-4 rounded-lg border ${
                  improvements.sharpeImprovement > 0
                    ? 'bg-amber-50 dark:bg-amber-900/20 border-amber-200 dark:border-amber-800'
                    : 'bg-gray-50 dark:bg-gray-700/50 border-gray-200 dark:border-gray-600'
                }`}>
                  <div className="flex items-center gap-2 mb-1">
                    <ChartBarIcon className={`w-5 h-5 ${
                      improvements.sharpeImprovement > 0 ? 'text-amber-500' : 'text-gray-400'
                    }`} />
                    <span className="text-sm font-medium text-gray-700 dark:text-gray-300">
                      Sharpe Ratio
                    </span>
                  </div>
                  <p className="text-2xl font-bold text-gray-900 dark:text-white">
                    {result.sharpeRatio.toFixed(2)}
                  </p>
                  {improvements.sharpeImprovement > 0 && (
                    <p className="text-xs text-amber-600 mt-1">
                      +{improvements.sharpeImprovement.toFixed(2)} vs actual ({result.currentSharpe.toFixed(2)})
                    </p>
                  )}
                </div>
              </div>
            )}

            {/* Efficient Frontier Chart */}
            <div className="mb-6">
              <h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3">
                Frontera Eficiente
              </h4>
              <div className="h-64 bg-gray-50 dark:bg-gray-700/50 rounded-lg p-4">
                <ResponsiveContainer width="100%" height="100%">
                  <ScatterChart margin={{ top: 10, right: 30, bottom: 10, left: 10 }}>
                    <CartesianGrid strokeDasharray="3 3" stroke="#374151" opacity={0.3} />
                    <XAxis
                      dataKey="risk"
                      type="number"
                      domain={[0, 60]}
                      name="Riesgo"
                      unit="%"
                      stroke="#9CA3AF"
                      fontSize={12}
                    />
                    <YAxis
                      dataKey="return"
                      type="number"
                      domain={[0, 50]}
                      name="Retorno"
                      unit="%"
                      stroke="#9CA3AF"
                      fontSize={12}
                    />
                    <Tooltip
                      contentStyle={{
                        backgroundColor: '#1F2937',
                        border: 'none',
                        borderRadius: '8px',
                        color: '#fff',
                      }}
                      formatter={(value: number, name: string) => [
                        `${value.toFixed(1)}%`,
                        name === 'risk' ? 'Riesgo' : 'Retorno',
                      ]}
                    />
                    {/* Frontier Line */}
                    <Scatter
                      data={efficientFrontier.filter((p) => !p.isCurrent && !p.isOptimal)}
                      fill="#6366F1"
                      line={{ stroke: '#6366F1', strokeWidth: 2 }}
                      shape="circle"
                    />
                    {/* Current Portfolio */}
                    <Scatter
                      data={efficientFrontier.filter((p) => p.isCurrent)}
                      fill="#EF4444"
                      shape="star"
                    >
                      {efficientFrontier
                        .filter((p) => p.isCurrent)
                        .map((_, index) => (
                          <Cell key={index} fill="#EF4444" />
                        ))}
                    </Scatter>
                    {/* Optimal Portfolio */}
                    <Scatter
                      data={efficientFrontier.filter((p) => p.isOptimal)}
                      fill="#10B981"
                      shape="diamond"
                    >
                      {efficientFrontier
                        .filter((p) => p.isOptimal)
                        .map((_, index) => (
                          <Cell key={index} fill="#10B981" />
                        ))}
                    </Scatter>
                  </ScatterChart>
                </ResponsiveContainer>
              </div>
              {/* Legend */}
              <div className="flex justify-center gap-6 mt-3 text-xs">
                <div className="flex items-center gap-1">
                  <div className="w-3 h-3 bg-indigo-500 rounded-full" />
                  <span className="text-gray-600 dark:text-gray-400">Frontera Eficiente</span>
                </div>
                <div className="flex items-center gap-1">
                  <div className="w-3 h-3 bg-red-500 rounded-full" />
                  <span className="text-gray-600 dark:text-gray-400">Portfolio Actual</span>
                </div>
                <div className="flex items-center gap-1">
                  <div className="w-3 h-3 bg-green-500 rounded-full" />
                  <span className="text-gray-600 dark:text-gray-400">Portfolio Optimo</span>
                </div>
              </div>
            </div>

            {/* Allocation Comparison */}
            <div className="mb-6">
              <h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-4">
                Comparacion de Allocacion (Actual vs Optima)
              </h4>
              <div className="space-y-4">
                {result.allocations.map((alloc) => (
                  <AllocationComparisonBar
                    key={alloc.asset}
                    asset={alloc.asset}
                    current={alloc.currentWeight}
                    optimal={alloc.optimalWeight}
                    color={ASSET_COLORS[alloc.asset] || '#6366F1'}
                  />
                ))}
              </div>
            </div>

            {/* Recommendations Table */}
            <div className="mb-6">
              <h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3">
                Ajustes Recomendados
              </h4>
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b border-gray-200 dark:border-gray-700">
                      <th className="text-left py-2 px-3 text-gray-500 dark:text-gray-400 font-medium">
                        Activo
                      </th>
                      <th className="text-right py-2 px-3 text-gray-500 dark:text-gray-400 font-medium">
                        Actual
                      </th>
                      <th className="text-right py-2 px-3 text-gray-500 dark:text-gray-400 font-medium">
                        Optimo
                      </th>
                      <th className="text-right py-2 px-3 text-gray-500 dark:text-gray-400 font-medium">
                        Cambio
                      </th>
                      <th className="text-right py-2 px-3 text-gray-500 dark:text-gray-400 font-medium">
                        Monto USD
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {result.allocations
                      .filter((a) => Math.abs(a.difference) >= 0.01)
                      .map((alloc) => {
                        const changeUSD = alloc.difference * totalValue;
                        return (
                          <tr
                            key={alloc.asset}
                            className="border-b border-gray-100 dark:border-gray-700/50"
                          >
                            <td className="py-2 px-3 font-medium text-gray-900 dark:text-white">
                              {alloc.asset}
                            </td>
                            <td className="py-2 px-3 text-right text-gray-600 dark:text-gray-400">
                              {(alloc.currentWeight * 100).toFixed(1)}%
                            </td>
                            <td className="py-2 px-3 text-right text-gray-900 dark:text-white">
                              {(alloc.optimalWeight * 100).toFixed(1)}%
                            </td>
                            <td className={`py-2 px-3 text-right font-medium ${
                              alloc.difference > 0 ? 'text-green-500' : 'text-red-500'
                            }`}>
                              {alloc.difference > 0 ? '+' : ''}{(alloc.difference * 100).toFixed(1)}%
                            </td>
                            <td className={`py-2 px-3 text-right font-medium ${
                              changeUSD > 0 ? 'text-green-500' : 'text-red-500'
                            }`}>
                              {changeUSD > 0 ? '+' : ''}${Math.abs(changeUSD).toLocaleString(undefined, { maximumFractionDigits: 0 })}
                            </td>
                          </tr>
                        );
                      })}
                  </tbody>
                </table>
              </div>
            </div>

            {/* Info Footer */}
            <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>
                  <p className="text-sm text-blue-800 dark:text-blue-200 font-medium">
                    Sobre la Optimizacion
                  </p>
                  <p className="text-xs text-blue-700 dark:text-blue-300 mt-1">
                    Esta optimizacion utiliza la Teoria Moderna de Portafolios (Markowitz) para
                    encontrar la combinacion de activos que maximiza el retorno ajustado por riesgo.
                    Los resultados son estimaciones basadas en datos historicos y no garantizan
                    rendimientos futuros.
                  </p>
                </div>
              </div>
            </div>
          </>
        ) : (
          <div className="text-center py-12 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
            <SparklesIcon className="w-12 h-12 text-gray-400 mx-auto mb-3" />
            <h4 className="font-medium text-gray-900 dark:text-white mb-1">
              Optimiza tu Portfolio
            </h4>
            <p className="text-sm text-gray-500 dark:text-gray-400 max-w-md mx-auto mb-4">
              El optimizador analiza tu portfolio actual y sugiere una allocacion
              optima basada en la Teoria Moderna de Portafolios, maximizando el
              ratio de Sharpe segun tu tolerancia al riesgo.
            </p>
            <button
              onClick={handleOptimize}
              disabled={isOptimizing}
              className="px-6 py-2 bg-amber-600 hover:bg-amber-700 text-white font-medium rounded-lg"
            >
              Ejecutar Optimizacion
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

export default AllocationOptimizer;
