/**
 * Investment Products Page
 * Displays available investment products (Atlas, Orion, Nova)
 */

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

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

interface InvestmentProduct {
  id: string;
  code: string;
  name: string;
  description: string;
  riskProfile: 'conservative' | 'moderate' | 'aggressive';
  targetReturnMin: number;
  targetReturnMax: number;
  maxDrawdown: number;
  minInvestment: number;
  managementFee: number;
  performanceFee: number;
  features: string[];
  strategy: string;
  assets: string[];
  tradingFrequency: string;
}

interface ProductStats {
  totalInvestors: number;
  totalAum: number;
  avgReturn: number;
  winRate: number;
}

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

async function fetchProducts(): Promise<InvestmentProduct[]> {
  const response = await fetch('/api/v1/investment/products');
  if (!response.ok) throw new Error('Failed to fetch products');
  const data = await response.json();
  return data.data;
}

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

const RiskBadge: React.FC<{ risk: string }> = ({ risk }) => {
  const colors = {
    conservative: 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200',
    moderate: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200',
    aggressive: 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200',
  };

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

  return (
    <span className={`px-3 py-1 rounded-full text-sm font-medium ${colors[risk as keyof typeof colors]}`}>
      {labels[risk as keyof typeof labels]}
    </span>
  );
};

interface ProductCardProps {
  product: InvestmentProduct;
}

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

  return (
    <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-lg overflow-hidden hover:shadow-xl transition-shadow">
      {/* Header */}
      <div className="p-6 border-b border-gray-200 dark:border-gray-700">
        <div className="flex items-center justify-between mb-4">
          <span className="text-4xl">{icons[product.code] || '📊'}</span>
          <RiskBadge risk={product.riskProfile} />
        </div>
        <h3 className="text-xl font-bold text-gray-900 dark:text-white mb-2">
          {product.name}
        </h3>
        <p className="text-gray-600 dark:text-gray-400 text-sm">
          {product.description}
        </p>
      </div>

      {/* Stats */}
      <div className="p-6 bg-gray-50 dark:bg-gray-900/50">
        <div className="grid grid-cols-2 gap-4 mb-6">
          <div>
            <p className="text-sm text-gray-500 dark:text-gray-400">Target Mensual</p>
            <p className="text-2xl font-bold text-green-600">
              {product.targetReturnMin}-{product.targetReturnMax}%
            </p>
          </div>
          <div>
            <p className="text-sm text-gray-500 dark:text-gray-400">Max Drawdown</p>
            <p className="text-2xl font-bold text-red-500">
              {product.maxDrawdown}%
            </p>
          </div>
        </div>

        <div className="space-y-3 mb-6">
          <div className="flex justify-between text-sm">
            <span className="text-gray-500 dark:text-gray-400">Inversión mínima</span>
            <span className="font-medium text-gray-900 dark:text-white">
              ${product.minInvestment.toLocaleString()}
            </span>
          </div>
          <div className="flex justify-between text-sm">
            <span className="text-gray-500 dark:text-gray-400">Estrategia</span>
            <span className="font-medium text-gray-900 dark:text-white">
              {product.strategy}
            </span>
          </div>
          <div className="flex justify-between text-sm">
            <span className="text-gray-500 dark:text-gray-400">Frecuencia</span>
            <span className="font-medium text-gray-900 dark:text-white">
              {product.tradingFrequency}
            </span>
          </div>
          <div className="flex justify-between text-sm">
            <span className="text-gray-500 dark:text-gray-400">Performance Fee</span>
            <span className="font-medium text-gray-900 dark:text-white">
              {product.performanceFee}%
            </span>
          </div>
        </div>

        {/* Features */}
        <div className="mb-6">
          <p className="text-sm text-gray-500 dark:text-gray-400 mb-2">Características</p>
          <div className="flex flex-wrap gap-2">
            {product.features.map((feature, index) => (
              <span
                key={index}
                className="px-2 py-1 bg-blue-100 dark:bg-blue-900/30 text-blue-800 dark:text-blue-200 text-xs rounded-full"
              >
                {feature}
              </span>
            ))}
          </div>
        </div>

        {/* CTA */}
        <Link
          to={`/investment/products/${product.id}`}
          className="block w-full text-center py-3 px-4 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors"
        >
          Ver Detalles
        </Link>
      </div>
    </div>
  );
};

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

export const Products: React.FC = () => {
  const [products, setProducts] = useState<InvestmentProduct[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [filter, setFilter] = useState<string>('all');

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

  const loadProducts = async () => {
    try {
      setLoading(true);
      const data = await fetchProducts();
      setProducts(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error loading products');
    } finally {
      setLoading(false);
    }
  };

  const filteredProducts = products.filter((p) =>
    filter === 'all' ? true : p.riskProfile === filter
  );

  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={loadProducts}
          className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
        >
          Reintentar
        </button>
      </div>
    );
  }

  return (
    <div className="max-w-7xl mx-auto px-4 py-8">
      {/* Header */}
      <div className="text-center mb-12">
        <h1 className="text-4xl font-bold text-gray-900 dark:text-white mb-4">
          Productos de Inversión
        </h1>
        <p className="text-xl text-gray-600 dark:text-gray-400 max-w-2xl mx-auto">
          Elige el agente de IA que mejor se adapte a tu perfil de riesgo y objetivos de inversión
        </p>
      </div>

      {/* Filters */}
      <div className="flex justify-center gap-2 mb-8">
        {[
          { value: 'all', label: 'Todos' },
          { value: 'conservative', label: 'Conservador' },
          { value: 'moderate', label: 'Moderado' },
          { value: 'aggressive', label: 'Agresivo' },
        ].map((option) => (
          <button
            key={option.value}
            onClick={() => setFilter(option.value)}
            className={`px-4 py-2 rounded-lg font-medium transition-colors ${
              filter === option.value
                ? 'bg-blue-600 text-white'
                : 'bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-600'
            }`}
          >
            {option.label}
          </button>
        ))}
      </div>

      {/* Products Grid */}
      <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-8">
        {filteredProducts.map((product) => (
          <ProductCard key={product.id} product={product} />
        ))}
      </div>

      {/* Disclaimer */}
      <div className="mt-12 p-6 bg-yellow-50 dark:bg-yellow-900/20 rounded-lg border border-yellow-200 dark:border-yellow-800">
        <p className="text-sm text-yellow-800 dark:text-yellow-200">
          <strong>Advertencia de riesgo:</strong> El trading de criptomonedas conlleva riesgos significativos.
          Los rendimientos pasados no garantizan rendimientos futuros. Solo invierte lo que puedas permitirte perder.
          OrbiQuant no es un asesor financiero registrado.
        </p>
      </div>
    </div>
  );
};

export default Products;
