/**
 * Portfolio Detail Page
 * Detailed view of a single portfolio with performance charts,
 * allocations, positions table, and advanced metrics
 */

import React, { useEffect, useState } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import {
  ArrowLeftIcon,
  ArrowPathIcon,
  PencilIcon,
  PlusIcon,
  ArrowsRightLeftIcon,
  ChartBarIcon,
  CurrencyDollarIcon,
  ArrowTrendingUpIcon,
  ArrowTrendingDownIcon,
  EllipsisVerticalIcon,
  TrashIcon,
  ShieldExclamationIcon,
  FlagIcon,
  SparklesIcon,
  TableCellsIcon,
} from '@heroicons/react/24/solid';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Area, AreaChart } from 'recharts';
import {
  getPortfolio,
  getPortfolioPerformance,
  type Portfolio,
  type PerformanceDataPoint,
  type PerformancePeriod,
} from '../../../services/portfolio.service';
import { usePortfolioStore } from '../../../stores/portfolioStore';
import { AllocationsCard } from '../components/AllocationsCard';
import { AllocationTable } from '../components/AllocationTable';
import { PerformanceMetricsCard } from '../components/PerformanceMetricsCard';
import { RebalanceModal } from '../components/RebalanceModal';
import { MonteCarloSimulator } from '../components/MonteCarloSimulator';
import { RebalancingPanel } from '../components/RebalancingPanel';
import { GoalsManager } from '../components/GoalsManager';
import { RiskAnalytics } from '../components/RiskAnalytics';
import { AllocationOptimizer } from '../components/AllocationOptimizer';
import { CorrelationMatrix } from '../components/CorrelationMatrix';

// ============================================================================
// Tab Types
// ============================================================================

type TabId = 'overview' | 'risk' | 'goals' | 'optimize' | 'simulate';

// ============================================================================
// Constants
// ============================================================================

const PERIOD_OPTIONS: { value: PerformancePeriod; label: string }[] = [
  { value: 'week', label: '7D' },
  { value: 'month', label: '1M' },
  { value: '3months', label: '3M' },
  { value: 'year', label: '1A' },
  { value: 'all', label: 'Todo' },
];

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

interface StatCardProps {
  label: string;
  value: string;
  change?: number;
  icon: React.ReactNode;
  color: string;
}

const StatCard: React.FC<StatCardProps> = ({ label, value, change, icon, color }) => {
  return (
    <div className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow-lg">
      <div className="flex items-center justify-between mb-2">
        <div className={`p-2 rounded-lg ${color}`}>{icon}</div>
        {change !== undefined && (
          <div
            className={`flex items-center gap-1 text-sm font-medium ${
              change >= 0 ? 'text-green-500' : 'text-red-500'
            }`}
          >
            {change >= 0 ? (
              <ArrowTrendingUpIcon className="w-4 h-4" />
            ) : (
              <ArrowTrendingDownIcon className="w-4 h-4" />
            )}
            {Math.abs(change).toFixed(2)}%
          </div>
        )}
      </div>
      <p className="text-xs text-gray-500 dark:text-gray-400">{label}</p>
      <p className="text-lg font-bold text-gray-900 dark:text-white mt-1">{value}</p>
    </div>
  );
};

interface PerformanceChartProps {
  data: PerformanceDataPoint[];
  period: PerformancePeriod;
  onPeriodChange: (period: PerformancePeriod) => void;
  loading: boolean;
}

const PerformanceChartSection: React.FC<PerformanceChartProps> = ({
  data,
  period,
  onPeriodChange,
  loading,
}) => {
  const isPositive = data.length > 0 && data[data.length - 1].value >= data[0].value;
  const totalChange = data.length > 0 ? data[data.length - 1].value - data[0].value : 0;
  const totalChangePercent = data.length > 0 && data[0].value > 0
    ? ((data[data.length - 1].value - data[0].value) / data[0].value) * 100
    : 0;

  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>
          <h3 className="font-bold text-gray-900 dark:text-white">Rendimiento Historico</h3>
          {data.length > 0 && (
            <div className="flex items-center gap-2 mt-1">
              <span
                className={`text-lg font-bold ${
                  isPositive ? 'text-green-500' : 'text-red-500'
                }`}
              >
                {isPositive ? '+' : ''}${totalChange.toLocaleString(undefined, {
                  minimumFractionDigits: 2,
                  maximumFractionDigits: 2,
                })}
              </span>
              <span
                className={`text-sm ${
                  isPositive ? 'text-green-500' : 'text-red-500'
                }`}
              >
                ({isPositive ? '+' : ''}{totalChangePercent.toFixed(2)}%)
              </span>
            </div>
          )}
        </div>
        <div className="flex gap-1">
          {PERIOD_OPTIONS.map((option) => (
            <button
              key={option.value}
              onClick={() => onPeriodChange(option.value)}
              className={`px-3 py-1 rounded text-sm font-medium transition-colors ${
                period === option.value
                  ? 'bg-blue-600 text-white'
                  : 'bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
              }`}
            >
              {option.label}
            </button>
          ))}
        </div>
      </div>

      {loading ? (
        <div className="flex items-center justify-center h-64">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
        </div>
      ) : (
        <ResponsiveContainer width="100%" height={280}>
          <AreaChart data={data}>
            <defs>
              <linearGradient id="colorValue" x1="0" y1="0" x2="0" y2="1">
                <stop
                  offset="5%"
                  stopColor={isPositive ? '#10B981' : '#EF4444'}
                  stopOpacity={0.3}
                />
                <stop
                  offset="95%"
                  stopColor={isPositive ? '#10B981' : '#EF4444'}
                  stopOpacity={0}
                />
              </linearGradient>
            </defs>
            <CartesianGrid strokeDasharray="3 3" stroke="#374151" opacity={0.3} />
            <XAxis
              dataKey="date"
              stroke="#9CA3AF"
              fontSize={12}
              tickFormatter={(value) => {
                const date = new Date(value);
                return `${date.getDate()}/${date.getMonth() + 1}`;
              }}
            />
            <YAxis
              stroke="#9CA3AF"
              fontSize={12}
              tickFormatter={(value) => `$${value.toLocaleString()}`}
              domain={['auto', 'auto']}
            />
            <Tooltip
              contentStyle={{
                backgroundColor: '#1F2937',
                border: 'none',
                borderRadius: '8px',
                color: '#fff',
              }}
              formatter={(value: number) => [
                `$${value.toLocaleString(undefined, { minimumFractionDigits: 2 })}`,
                'Valor',
              ]}
              labelFormatter={(label) => new Date(label).toLocaleDateString()}
            />
            <Area
              type="monotone"
              dataKey="value"
              stroke={isPositive ? '#10B981' : '#EF4444'}
              strokeWidth={2}
              fill="url(#colorValue)"
            />
          </AreaChart>
        </ResponsiveContainer>
      )}
    </div>
  );
};

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

// Mock goals data for demo
const generateMockGoals = () => [
  {
    id: 'g1',
    userId: 'user-1',
    name: 'Fondo de Emergencia',
    targetAmount: 10000,
    currentAmount: 6500,
    targetDate: new Date(Date.now() + 180 * 24 * 60 * 60 * 1000).toISOString(),
    monthlyContribution: 500,
    progress: 65,
    projectedCompletion: new Date(Date.now() + 150 * 24 * 60 * 60 * 1000).toISOString(),
    status: 'on_track' as const,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  },
  {
    id: 'g2',
    userId: 'user-1',
    name: 'Vacaciones 2027',
    targetAmount: 5000,
    currentAmount: 1200,
    targetDate: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toISOString(),
    monthlyContribution: 300,
    progress: 24,
    projectedCompletion: new Date(Date.now() + 400 * 24 * 60 * 60 * 1000).toISOString(),
    status: 'at_risk' as const,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  },
];

export default function PortfolioDetailPage() {
  const { portfolioId } = useParams<{ portfolioId: string }>();
  const navigate = useNavigate();

  // Local state
  const [portfolio, setPortfolio] = useState<Portfolio | null>(null);
  const [performanceData, setPerformanceData] = useState<PerformanceDataPoint[]>([]);
  const [period, setPeriod] = useState<PerformancePeriod>('month');
  const [loading, setLoading] = useState(true);
  const [loadingPerformance, setLoadingPerformance] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showRebalanceModal, setShowRebalanceModal] = useState(false);
  const [showActions, setShowActions] = useState(false);
  const [activeTab, setActiveTab] = useState<TabId>('overview');
  const [goals] = useState(generateMockGoals());

  // Store
  const { fetchPortfolios } = usePortfolioStore();

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

  useEffect(() => {
    if (portfolioId) {
      loadPerformance();
    }
  }, [portfolioId, period]);

  const loadPortfolio = async () => {
    if (!portfolioId) return;

    try {
      setLoading(true);
      setError(null);
      const data = await getPortfolio(portfolioId);
      setPortfolio(data);
    } catch (err) {
      console.error('Error loading portfolio:', err);
      setError(err instanceof Error ? err.message : 'Error al cargar portfolio');
      // Generate mock portfolio for demo
      setPortfolio(generateMockPortfolio(portfolioId));
    } finally {
      setLoading(false);
    }
  };

  const loadPerformance = async () => {
    if (!portfolioId) return;

    try {
      setLoadingPerformance(true);
      const data = await getPortfolioPerformance(portfolioId, period);
      setPerformanceData(data);
    } catch (err) {
      console.error('Error loading performance:', err);
      setPerformanceData(generateMockPerformance(period));
    } finally {
      setLoadingPerformance(false);
    }
  };

  const generateMockPortfolio = (id: string): Portfolio => ({
    id,
    userId: 'user-1',
    name: 'Mi Portfolio Principal',
    riskProfile: 'moderate',
    allocations: [
      { id: '1', portfolioId: id, asset: 'BTC', targetPercent: 40, currentPercent: 38.5, quantity: 0.25, value: 11250, cost: 9500, pnl: 1750, pnlPercent: 18.4, deviation: -1.5 },
      { id: '2', portfolioId: id, asset: 'ETH', targetPercent: 30, currentPercent: 32.1, quantity: 3.5, value: 9380, cost: 8200, pnl: 1180, pnlPercent: 14.4, deviation: 2.1 },
      { id: '3', portfolioId: id, asset: 'SOL', targetPercent: 15, currentPercent: 14.2, quantity: 42, value: 4150, cost: 3800, pnl: 350, pnlPercent: 9.2, deviation: -0.8 },
      { id: '4', portfolioId: id, asset: 'LINK', targetPercent: 10, currentPercent: 10.5, quantity: 180, value: 3070, cost: 2900, pnl: 170, pnlPercent: 5.9, deviation: 0.5 },
      { id: '5', portfolioId: id, asset: 'USDT', targetPercent: 5, currentPercent: 4.7, quantity: 1375, value: 1375, cost: 1375, pnl: 0, pnlPercent: 0, deviation: -0.3 },
    ],
    totalValue: 29225,
    totalCost: 25775,
    unrealizedPnl: 3450,
    unrealizedPnlPercent: 13.39,
    realizedPnl: 1250,
    lastRebalanced: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(),
    createdAt: new Date(Date.now() - 180 * 24 * 60 * 60 * 1000).toISOString(),
    updatedAt: new Date().toISOString(),
  });

  const generateMockPerformance = (p: PerformancePeriod): PerformanceDataPoint[] => {
    const days = p === 'week' ? 7 : p === 'month' ? 30 : p === '3months' ? 90 : p === 'year' ? 365 : 180;
    const data: PerformanceDataPoint[] = [];
    let value = 25000;

    for (let i = days; i >= 0; i--) {
      const date = new Date();
      date.setDate(date.getDate() - i);
      const change = (Math.random() - 0.4) * value * 0.02;
      value += change;

      data.push({
        date: date.toISOString().split('T')[0],
        value,
        pnl: value - 25000,
        pnlPercent: ((value - 25000) / 25000) * 100,
        change,
        changePercent: (change / (value - change)) * 100,
      });
    }
    return data;
  };

  const handleRebalanceSuccess = () => {
    loadPortfolio();
    fetchPortfolios();
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
      </div>
    );
  }

  if (error && !portfolio) {
    return (
      <div className="flex flex-col items-center justify-center min-h-screen">
        <p className="text-red-500 mb-4">{error}</p>
        <button
          onClick={loadPortfolio}
          className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
        >
          Reintentar
        </button>
      </div>
    );
  }

  if (!portfolio) return null;

  const riskProfileLabels = {
    conservative: 'Conservador',
    moderate: 'Moderado',
    aggressive: 'Agresivo',
  };

  return (
    <div className="max-w-7xl mx-auto px-4 py-8">
      {/* Header */}
      <div className="flex items-center justify-between mb-8">
        <div className="flex items-center gap-4">
          <button
            onClick={() => navigate('/portfolio')}
            className="p-2 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors"
          >
            <ArrowLeftIcon className="w-5 h-5 text-gray-600 dark:text-gray-300" />
          </button>
          <div>
            <h1 className="text-2xl font-bold text-gray-900 dark:text-white">
              {portfolio.name}
            </h1>
            <div className="flex items-center gap-3 mt-1">
              <span className="text-sm text-gray-500 dark:text-gray-400">
                Perfil: {riskProfileLabels[portfolio.riskProfile]}
              </span>
              <span className="text-gray-300 dark:text-gray-600">|</span>
              <span className="text-sm text-gray-500 dark:text-gray-400">
                {portfolio.allocations.length} activos
              </span>
            </div>
          </div>
        </div>

        <div className="flex items-center gap-3">
          <button
            onClick={loadPortfolio}
            className="p-2 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors"
          >
            <ArrowPathIcon className="w-5 h-5 text-gray-600 dark:text-gray-300" />
          </button>
          <button
            onClick={() => setShowRebalanceModal(true)}
            className="px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white font-medium rounded-lg transition-colors flex items-center gap-2"
          >
            <ArrowsRightLeftIcon className="w-5 h-5" />
            Rebalancear
          </button>
          <Link
            to={`/portfolio/${portfolioId}/edit`}
            className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors flex items-center gap-2"
          >
            <PlusIcon className="w-5 h-5" />
            Agregar
          </Link>
          <div className="relative">
            <button
              onClick={() => setShowActions(!showActions)}
              className="p-2 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors"
            >
              <EllipsisVerticalIcon className="w-5 h-5 text-gray-600 dark:text-gray-300" />
            </button>
            {showActions && (
              <div className="absolute right-0 mt-2 w-48 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700 z-10">
                <Link
                  to={`/portfolio/${portfolioId}/edit`}
                  className="flex items-center gap-2 px-4 py-3 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
                >
                  <PencilIcon className="w-4 h-4 text-gray-500" />
                  <span className="text-gray-700 dark:text-gray-300">Editar Portfolio</span>
                </Link>
                <button
                  className="flex items-center gap-2 px-4 py-3 w-full hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors text-red-600"
                >
                  <TrashIcon className="w-4 h-4" />
                  <span>Eliminar Portfolio</span>
                </button>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Stats Grid */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
        <StatCard
          label="Valor Total"
          value={`$${portfolio.totalValue.toLocaleString(undefined, { minimumFractionDigits: 2 })}`}
          icon={<CurrencyDollarIcon className="w-5 h-5 text-blue-600" />}
          color="bg-blue-100 dark:bg-blue-900/30"
        />
        <StatCard
          label="P&L No Realizado"
          value={`${portfolio.unrealizedPnl >= 0 ? '+' : ''}$${Math.abs(portfolio.unrealizedPnl).toLocaleString(undefined, { minimumFractionDigits: 2 })}`}
          change={portfolio.unrealizedPnlPercent}
          icon={<ArrowTrendingUpIcon className="w-5 h-5 text-green-600" />}
          color="bg-green-100 dark:bg-green-900/30"
        />
        <StatCard
          label="Costo Base"
          value={`$${portfolio.totalCost.toLocaleString(undefined, { minimumFractionDigits: 2 })}`}
          icon={<ChartBarIcon className="w-5 h-5 text-purple-600" />}
          color="bg-purple-100 dark:bg-purple-900/30"
        />
        <StatCard
          label="P&L Realizado"
          value={`${portfolio.realizedPnl >= 0 ? '+' : ''}$${Math.abs(portfolio.realizedPnl).toLocaleString(undefined, { minimumFractionDigits: 2 })}`}
          icon={<CurrencyDollarIcon className="w-5 h-5 text-orange-600" />}
          color="bg-orange-100 dark:bg-orange-900/30"
        />
      </div>

      {/* Performance Chart */}
      <div className="mb-8">
        <PerformanceChartSection
          data={performanceData}
          period={period}
          onPeriodChange={setPeriod}
          loading={loadingPerformance}
        />
      </div>

      {/* Tab Navigation */}
      <div className="mb-8">
        <div className="flex gap-1 bg-gray-100 dark:bg-gray-700 rounded-xl p-1.5 overflow-x-auto">
          <button
            onClick={() => setActiveTab('overview')}
            className={`flex items-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-colors whitespace-nowrap ${
              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 dark:hover:text-white'
            }`}
          >
            <ChartBarIcon className="w-4 h-4" />
            Resumen
          </button>
          <button
            onClick={() => setActiveTab('risk')}
            className={`flex items-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-colors whitespace-nowrap ${
              activeTab === 'risk'
                ? '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 dark:hover:text-white'
            }`}
          >
            <ShieldExclamationIcon className="w-4 h-4" />
            Riesgo
          </button>
          <button
            onClick={() => setActiveTab('goals')}
            className={`flex items-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-colors whitespace-nowrap ${
              activeTab === 'goals'
                ? '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 dark:hover:text-white'
            }`}
          >
            <FlagIcon className="w-4 h-4" />
            Metas
          </button>
          <button
            onClick={() => setActiveTab('optimize')}
            className={`flex items-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-colors whitespace-nowrap ${
              activeTab === 'optimize'
                ? '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 dark:hover:text-white'
            }`}
          >
            <SparklesIcon className="w-4 h-4" />
            Optimizar
          </button>
          <button
            onClick={() => setActiveTab('simulate')}
            className={`flex items-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-colors whitespace-nowrap ${
              activeTab === 'simulate'
                ? '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 dark:hover:text-white'
            }`}
          >
            <TableCellsIcon className="w-4 h-4" />
            Simular
          </button>
        </div>
      </div>

      {/* Tab Content */}
      {activeTab === 'overview' && (
        <div className="grid lg:grid-cols-3 gap-8">
          {/* Left Column: Allocations & Positions */}
          <div className="lg:col-span-2 space-y-8">
            {/* Allocations Chart */}
            <AllocationsCard
              allocations={portfolio.allocations}
              showTargetComparison={true}
              onRebalance={() => setShowRebalanceModal(true)}
              maxDriftThreshold={5}
            />

            {/* Positions Table */}
            <div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
              <div className="flex items-center justify-between mb-4">
                <h3 className="font-bold text-gray-900 dark:text-white">
                  Detalle de Posiciones
                </h3>
                <Link
                  to={`/portfolio/${portfolioId}/edit`}
                  className="text-sm text-blue-600 hover:text-blue-700"
                >
                  Editar Allocaciones
                </Link>
              </div>
              <AllocationTable
                allocations={portfolio.allocations}
                showDeviation={true}
              />
            </div>
          </div>

          {/* Right Column: Metrics */}
          <div className="space-y-8">
            <PerformanceMetricsCard
              portfolioId={portfolio.id}
              compact={false}
            />

            {/* Portfolio Info */}
            <div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
              <h3 className="font-bold text-gray-900 dark:text-white mb-4">
                Informacion del Portfolio
              </h3>
              <div className="space-y-3 text-sm">
                <div className="flex justify-between">
                  <span className="text-gray-500 dark:text-gray-400">Perfil de Riesgo</span>
                  <span className="text-gray-900 dark:text-white">
                    {riskProfileLabels[portfolio.riskProfile]}
                  </span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-500 dark:text-gray-400">Ultimo Rebalanceo</span>
                  <span className="text-gray-900 dark:text-white">
                    {portfolio.lastRebalanced
                      ? new Date(portfolio.lastRebalanced).toLocaleDateString()
                      : 'Nunca'}
                  </span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-500 dark:text-gray-400">Creado</span>
                  <span className="text-gray-900 dark:text-white">
                    {new Date(portfolio.createdAt).toLocaleDateString()}
                  </span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-500 dark:text-gray-400">Actualizado</span>
                  <span className="text-gray-900 dark:text-white">
                    {new Date(portfolio.updatedAt).toLocaleString()}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Risk Tab */}
      {activeTab === 'risk' && (
        <div className="grid lg:grid-cols-2 gap-8">
          <RiskAnalytics
            portfolioId={portfolio.id}
            allocations={portfolio.allocations}
          />
          <div className="space-y-8">
            <CorrelationMatrix allocations={portfolio.allocations} />
            <RebalancingPanel
              portfolioId={portfolio.id}
              allocations={portfolio.allocations}
              onRebalance={() => setShowRebalanceModal(true)}
              lastRebalanced={portfolio.lastRebalanced}
            />
          </div>
        </div>
      )}

      {/* Goals Tab */}
      {activeTab === 'goals' && (
        <div className="max-w-4xl mx-auto">
          <GoalsManager
            goals={goals}
            onCreateGoal={() => navigate(`/portfolio/${portfolioId}/goals/new`)}
            onEditGoal={(goalId) => navigate(`/portfolio/${portfolioId}/goals/${goalId}/edit`)}
            onDeleteGoal={(goalId) => console.log('Delete goal:', goalId)}
            onUpdateProgress={(goalId, amount) => console.log('Update progress:', goalId, amount)}
          />
        </div>
      )}

      {/* Optimize Tab */}
      {activeTab === 'optimize' && (
        <div className="max-w-5xl mx-auto">
          <AllocationOptimizer
            portfolioId={portfolio.id}
            allocations={portfolio.allocations}
            totalValue={portfolio.totalValue}
          />
        </div>
      )}

      {/* Simulate Tab */}
      {activeTab === 'simulate' && (
        <div className="max-w-5xl mx-auto">
          <MonteCarloSimulator
            portfolioId={portfolio.id}
            currentValue={portfolio.totalValue}
            annualReturn={0.15}
            volatility={0.25}
          />
        </div>
      )}

      {/* Rebalance Modal */}
      <RebalanceModal
        isOpen={showRebalanceModal}
        onClose={() => setShowRebalanceModal(false)}
        portfolioId={portfolio.id}
        onSuccess={handleRebalanceSuccess}
      />

      {/* Click outside to close actions menu */}
      {showActions && (
        <div
          className="fixed inset-0 z-0"
          onClick={() => setShowActions(false)}
        />
      )}
    </div>
  );
}
