/**
 * Investment Portfolio Page
 * Dashboard showing user's investment accounts and performance
 */

import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';

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

interface InvestmentAccount {
  id: string;
  productId: string;
  product: {
    code: string;
    name: string;
    riskProfile: string;
  };
  status: 'active' | 'suspended' | 'closed';
  balance: number;
  initialInvestment: number;
  totalDeposited: number;
  totalWithdrawn: number;
  totalEarnings: number;
  unrealizedPnl: number;
  unrealizedPnlPercent: number;
  openedAt: string;
}

interface AccountSummary {
  totalBalance: number;
  totalEarnings: number;
  totalDeposited: number;
  totalWithdrawn: number;
  overallReturn: number;
  overallReturnPercent: number;
  accounts: InvestmentAccount[];
}

interface PerformanceData {
  date: string;
  balance: number;
  pnl: number;
}

// ============================================================================
// API Functions
// ============================================================================

async function fetchPortfolio(): Promise<AccountSummary> {
  const response = await fetch('/api/v1/investment/accounts/summary');
  if (!response.ok) throw new Error('Failed to fetch portfolio');
  const data = await response.json();
  return data.data;
}

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

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

const StatCard: React.FC<StatCardProps> = ({ label, value, change, icon, color }) => {
  const isPositive = (change || 0) >= 0;

  return (
    <div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-lg">
      <div className="flex items-center justify-between mb-4">
        <div className={`p-3 rounded-lg ${color}`}>{icon}</div>
        {change !== undefined && (
          <span className={`text-sm font-medium ${isPositive ? 'text-green-500' : 'text-red-500'}`}>
            {isPositive ? '+' : ''}
            {change.toFixed(2)}%
          </span>
        )}
      </div>
      <p className="text-sm text-gray-500 dark:text-gray-400">{label}</p>
      <p className="text-2xl font-bold text-gray-900 dark:text-white">{value}</p>
    </div>
  );
};

interface AccountRowProps {
  account: InvestmentAccount;
}

const AccountRow: React.FC<AccountRowProps> = ({ account }) => {
  const icons: Record<string, string> = {
    atlas: '🛡️',
    orion: '🔭',
    nova: '⭐',
  };

  const statusColors = {
    active: 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200',
    suspended: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200',
    closed: 'bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200',
  };

  const totalReturn = account.balance - account.totalDeposited + account.totalWithdrawn;
  const returnPercent = account.totalDeposited > 0
    ? (totalReturn / account.totalDeposited) * 100
    : 0;

  return (
    <Link
      to={`/investment/accounts/${account.id}`}
      className="block bg-white dark:bg-gray-800 rounded-xl p-6 shadow-lg hover:shadow-xl transition-shadow"
    >
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-3">
          <span className="text-3xl">{icons[account.product.code] || '📊'}</span>
          <div>
            <h3 className="font-bold text-gray-900 dark:text-white">
              {account.product.name}
            </h3>
            <p className="text-sm text-gray-500 dark:text-gray-400">
              Desde {new Date(account.openedAt).toLocaleDateString()}
            </p>
          </div>
        </div>
        <span className={`px-3 py-1 rounded-full text-sm font-medium ${statusColors[account.status]}`}>
          {account.status === 'active' ? 'Activa' : account.status === 'suspended' ? 'Suspendida' : 'Cerrada'}
        </span>
      </div>

      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div>
          <p className="text-sm text-gray-500 dark:text-gray-400">Balance</p>
          <p className="text-xl font-bold text-gray-900 dark:text-white">
            ${account.balance.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
          </p>
        </div>
        <div>
          <p className="text-sm text-gray-500 dark:text-gray-400">Invertido</p>
          <p className="text-xl font-bold text-gray-900 dark:text-white">
            ${account.totalDeposited.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
          </p>
        </div>
        <div>
          <p className="text-sm text-gray-500 dark:text-gray-400">Ganancias</p>
          <p className={`text-xl font-bold ${totalReturn >= 0 ? 'text-green-500' : 'text-red-500'}`}>
            {totalReturn >= 0 ? '+' : ''}
            ${Math.abs(totalReturn).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
          </p>
        </div>
        <div>
          <p className="text-sm text-gray-500 dark:text-gray-400">Retorno</p>
          <p className={`text-xl font-bold ${returnPercent >= 0 ? 'text-green-500' : 'text-red-500'}`}>
            {returnPercent >= 0 ? '+' : ''}
            {returnPercent.toFixed(2)}%
          </p>
        </div>
      </div>

      {account.unrealizedPnl !== 0 && (
        <div className="mt-4 pt-4 border-t border-gray-200 dark:border-gray-700">
          <div className="flex justify-between text-sm">
            <span className="text-gray-500 dark:text-gray-400">P&L No Realizado</span>
            <span className={account.unrealizedPnl >= 0 ? 'text-green-500' : 'text-red-500'}>
              {account.unrealizedPnl >= 0 ? '+' : ''}
              ${Math.abs(account.unrealizedPnl).toFixed(2)} ({account.unrealizedPnlPercent.toFixed(2)}%)
            </span>
          </div>
        </div>
      )}
    </Link>
  );
};

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

export const Portfolio: React.FC = () => {
  const [portfolio, setPortfolio] = useState<AccountSummary | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

  const loadPortfolio = async () => {
    try {
      setLoading(true);
      const data = await fetchPortfolio();
      setPortfolio(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error loading portfolio');
    } finally {
      setLoading(false);
    }
  };

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

  if (error) {
    return (
      <div className="flex flex-col items-center justify-center min-h-96">
        <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 activeAccounts = portfolio.accounts.filter((a) => a.status === 'active');

  return (
    <div className="max-w-7xl mx-auto px-4 py-8">
      {/* Header */}
      <div className="flex items-center justify-between mb-8">
        <div>
          <h1 className="text-3xl font-bold text-gray-900 dark:text-white">
            Mi Portfolio
          </h1>
          <p className="text-gray-600 dark:text-gray-400 mt-1">
            Gestiona tus inversiones con agentes IA
          </p>
        </div>
        <Link
          to="/investment/products"
          className="px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors"
        >
          + Nueva Inversión
        </Link>
      </div>

      {/* Summary Stats */}
      <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        <StatCard
          label="Valor Total"
          value={`$${portfolio.totalBalance.toLocaleString(undefined, { minimumFractionDigits: 2 })}`}
          icon={<span className="text-2xl">💰</span>}
          color="bg-blue-100 dark:bg-blue-900/30"
        />
        <StatCard
          label="Total Invertido"
          value={`$${portfolio.totalDeposited.toLocaleString(undefined, { minimumFractionDigits: 2 })}`}
          icon={<span className="text-2xl">📥</span>}
          color="bg-purple-100 dark:bg-purple-900/30"
        />
        <StatCard
          label="Ganancias Totales"
          value={`$${Math.abs(portfolio.overallReturn).toLocaleString(undefined, { minimumFractionDigits: 2 })}`}
          change={portfolio.overallReturnPercent}
          icon={<span className="text-2xl">📈</span>}
          color="bg-green-100 dark:bg-green-900/30"
        />
        <StatCard
          label="Cuentas Activas"
          value={activeAccounts.length}
          icon={<span className="text-2xl">🤖</span>}
          color="bg-orange-100 dark:bg-orange-900/30"
        />
      </div>

      {/* Accounts List */}
      {portfolio.accounts.length === 0 ? (
        <div className="text-center py-16 bg-white dark:bg-gray-800 rounded-xl shadow-lg">
          <span className="text-6xl mb-4 block">📊</span>
          <h3 className="text-xl font-bold text-gray-900 dark:text-white mb-2">
            Aún no tienes inversiones
          </h3>
          <p className="text-gray-600 dark:text-gray-400 mb-6">
            Comienza a invertir con nuestros agentes de IA
          </p>
          <Link
            to="/investment/products"
            className="inline-block px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors"
          >
            Ver Productos
          </Link>
        </div>
      ) : (
        <div className="space-y-4">
          <h2 className="text-xl font-bold text-gray-900 dark:text-white">
            Mis Cuentas
          </h2>
          {portfolio.accounts.map((account) => (
            <AccountRow key={account.id} account={account} />
          ))}
        </div>
      )}

      {/* Quick Actions */}
      <div className="mt-8 grid md:grid-cols-3 gap-4">
        <Link
          to="/investment/withdrawals"
          className="flex items-center gap-3 p-4 bg-white dark:bg-gray-800 rounded-xl shadow hover:shadow-lg transition-shadow"
        >
          <span className="text-2xl">💸</span>
          <div>
            <h4 className="font-medium text-gray-900 dark:text-white">Retiros</h4>
            <p className="text-sm text-gray-500 dark:text-gray-400">Ver solicitudes</p>
          </div>
        </Link>
        <Link
          to="/investment/transactions"
          className="flex items-center gap-3 p-4 bg-white dark:bg-gray-800 rounded-xl shadow hover:shadow-lg transition-shadow"
        >
          <span className="text-2xl">📋</span>
          <div>
            <h4 className="font-medium text-gray-900 dark:text-white">Transacciones</h4>
            <p className="text-sm text-gray-500 dark:text-gray-400">Historial completo</p>
          </div>
        </Link>
        <Link
          to="/investment/reports"
          className="flex items-center gap-3 p-4 bg-white dark:bg-gray-800 rounded-xl shadow hover:shadow-lg transition-shadow"
        >
          <span className="text-2xl">📊</span>
          <div>
            <h4 className="font-medium text-gray-900 dark:text-white">Reportes</h4>
            <p className="text-sm text-gray-500 dark:text-gray-400">Análisis detallado</p>
          </div>
        </Link>
      </div>
    </div>
  );
};

export default Portfolio;
