/**
 * ProductCard Component
 * Enhanced card for displaying investment product information
 * Epic: OQI-004 Cuentas de Inversion
 */

import React from 'react';
import { Link } from 'react-router-dom';
import {
  Shield,
  TrendingUp,
  Zap,
  Clock,
  AlertTriangle,
  ChevronRight,
  Star,
  Users,
} from 'lucide-react';

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

export type ProductStatus = 'open' | 'closed' | 'coming_soon' | 'limited';

export interface ProductCardProps {
  id: string;
  code: string;
  name: string;
  description: string;
  riskProfile: 'conservative' | 'moderate' | 'aggressive';
  targetReturnMin: number;
  targetReturnMax: number;
  maxDrawdown: number;
  minInvestment: number;
  managementFee?: number;
  performanceFee?: number;
  status?: ProductStatus;
  historicalReturn?: number;
  totalInvestors?: number;
  aum?: number;
  isNew?: boolean;
  isFeatured?: boolean;
  onInvest?: (productId: string) => void;
  compact?: boolean;
}

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

const RiskBadge: React.FC<{ risk: string; size?: 'sm' | 'md' }> = ({
  risk,
  size = 'md',
}) => {
  const config = {
    conservative: {
      color: 'text-emerald-400',
      bg: 'bg-emerald-500/20',
      border: 'border-emerald-500/30',
      label: 'Conservador',
      icon: Shield,
    },
    moderate: {
      color: 'text-amber-400',
      bg: 'bg-amber-500/20',
      border: 'border-amber-500/30',
      label: 'Moderado',
      icon: TrendingUp,
    },
    aggressive: {
      color: 'text-red-400',
      bg: 'bg-red-500/20',
      border: 'border-red-500/30',
      label: 'Agresivo',
      icon: Zap,
    },
  };

  const c = config[risk as keyof typeof config] || config.moderate;
  const Icon = c.icon;
  const sizeClasses = size === 'sm' ? 'px-2 py-0.5 text-xs' : 'px-3 py-1 text-sm';

  return (
    <span
      className={`inline-flex items-center gap-1.5 rounded-full font-medium ${sizeClasses} ${c.bg} ${c.color} border ${c.border}`}
    >
      <Icon className={size === 'sm' ? 'w-3 h-3' : 'w-4 h-4'} />
      {c.label}
    </span>
  );
};

const StatusBadge: React.FC<{ status: ProductStatus }> = ({ status }) => {
  const config = {
    open: {
      color: 'text-emerald-400',
      bg: 'bg-emerald-500/20',
      label: 'Abierto',
      dot: 'bg-emerald-400',
    },
    closed: {
      color: 'text-gray-400',
      bg: 'bg-gray-500/20',
      label: 'Cerrado',
      dot: 'bg-gray-400',
    },
    coming_soon: {
      color: 'text-blue-400',
      bg: 'bg-blue-500/20',
      label: 'Proximamente',
      dot: 'bg-blue-400',
    },
    limited: {
      color: 'text-amber-400',
      bg: 'bg-amber-500/20',
      label: 'Cupo Limitado',
      dot: 'bg-amber-400',
    },
  };

  const c = config[status];

  return (
    <span
      className={`inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-medium ${c.bg} ${c.color}`}
    >
      <span className={`w-1.5 h-1.5 rounded-full ${c.dot} animate-pulse`} />
      {c.label}
    </span>
  );
};

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

export const ProductCard: React.FC<ProductCardProps> = ({
  id,
  code,
  name,
  description,
  riskProfile,
  targetReturnMin,
  targetReturnMax,
  maxDrawdown,
  minInvestment,
  managementFee,
  performanceFee,
  status = 'open',
  historicalReturn,
  totalInvestors,
  aum,
  isNew,
  isFeatured,
  onInvest,
  compact = false,
}) => {
  const icons: Record<string, React.ReactNode> = {
    atlas: <Shield className="w-6 h-6 text-blue-400" />,
    orion: <TrendingUp className="w-6 h-6 text-purple-400" />,
    nova: <Zap className="w-6 h-6 text-amber-400" />,
  };

  const isAvailable = status === 'open' || status === 'limited';

  if (compact) {
    return (
      <Link
        to={`/investment/products/${id}`}
        className="flex items-center gap-4 p-4 rounded-xl bg-slate-800/50 border border-slate-700 hover:border-slate-600 transition-all group"
      >
        <div className="w-12 h-12 rounded-lg bg-slate-700 flex items-center justify-center">
          {icons[code] || <TrendingUp className="w-6 h-6 text-slate-400" />}
        </div>
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2">
            <h3 className="font-semibold text-white truncate">{name}</h3>
            {isNew && (
              <span className="px-1.5 py-0.5 rounded text-xs bg-blue-500/20 text-blue-400">
                Nuevo
              </span>
            )}
          </div>
          <div className="flex items-center gap-3 mt-1">
            <RiskBadge risk={riskProfile} size="sm" />
            <span className="text-sm text-emerald-400 font-medium">
              {targetReturnMin}-{targetReturnMax}%
            </span>
          </div>
        </div>
        <ChevronRight className="w-5 h-5 text-slate-500 group-hover:text-blue-400 transition-colors" />
      </Link>
    );
  }

  return (
    <div
      className={`relative rounded-2xl border overflow-hidden transition-all ${
        isFeatured
          ? 'bg-gradient-to-br from-blue-900/30 to-purple-900/30 border-blue-500/30'
          : 'bg-slate-800/50 border-slate-700 hover:border-slate-600'
      }`}
    >
      {/* Featured/New Badges */}
      {(isFeatured || isNew) && (
        <div className="absolute top-4 right-4 flex gap-2">
          {isFeatured && (
            <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium bg-amber-500/20 text-amber-400 border border-amber-500/30">
              <Star className="w-3 h-3" />
              Destacado
            </span>
          )}
          {isNew && (
            <span className="px-2 py-1 rounded-full text-xs font-medium bg-blue-500/20 text-blue-400 border border-blue-500/30">
              Nuevo
            </span>
          )}
        </div>
      )}

      {/* Header */}
      <div className="p-6">
        <div className="flex items-start gap-4 mb-4">
          <div className="w-14 h-14 rounded-xl bg-slate-700 flex items-center justify-center">
            {icons[code] || <TrendingUp className="w-7 h-7 text-slate-400" />}
          </div>
          <div className="flex-1">
            <div className="flex items-center gap-2 mb-1">
              <h3 className="text-xl font-bold text-white">{name}</h3>
              <StatusBadge status={status} />
            </div>
            <RiskBadge risk={riskProfile} />
          </div>
        </div>

        <p className="text-slate-400 text-sm mb-6 line-clamp-2">{description}</p>

        {/* Stats Grid */}
        <div className="grid grid-cols-2 gap-4 mb-6">
          <div className="p-3 rounded-lg bg-slate-900/50">
            <p className="text-xs text-slate-500 mb-1">Target Mensual</p>
            <p className="text-xl font-bold text-emerald-400">
              {targetReturnMin}-{targetReturnMax}%
            </p>
          </div>
          <div className="p-3 rounded-lg bg-slate-900/50">
            <p className="text-xs text-slate-500 mb-1">Max Drawdown</p>
            <p className="text-xl font-bold text-red-400">{maxDrawdown}%</p>
          </div>
        </div>

        {/* Additional Info */}
        <div className="space-y-2 text-sm">
          <div className="flex justify-between">
            <span className="text-slate-500">Inversion Minima</span>
            <span className="font-medium text-white">${minInvestment.toLocaleString()}</span>
          </div>
          {historicalReturn !== undefined && (
            <div className="flex justify-between">
              <span className="text-slate-500">Rendimiento Historico</span>
              <span
                className={`font-medium ${
                  historicalReturn >= 0 ? 'text-emerald-400' : 'text-red-400'
                }`}
              >
                {historicalReturn >= 0 ? '+' : ''}
                {historicalReturn.toFixed(1)}%
              </span>
            </div>
          )}
          {performanceFee !== undefined && (
            <div className="flex justify-between">
              <span className="text-slate-500">Performance Fee</span>
              <span className="font-medium text-white">{performanceFee}%</span>
            </div>
          )}
          {totalInvestors !== undefined && (
            <div className="flex justify-between">
              <span className="text-slate-500 flex items-center gap-1">
                <Users className="w-3 h-3" />
                Inversores
              </span>
              <span className="font-medium text-white">{totalInvestors.toLocaleString()}</span>
            </div>
          )}
        </div>
      </div>

      {/* Actions */}
      <div className="p-4 border-t border-slate-700/50 bg-slate-900/30">
        <div className="flex gap-3">
          <Link
            to={`/investment/products/${id}`}
            className="flex-1 py-2.5 text-center text-sm font-medium text-slate-300 bg-slate-700 hover:bg-slate-600 rounded-lg transition-colors"
          >
            Ver Detalles
          </Link>
          {isAvailable ? (
            onInvest ? (
              <button
                onClick={() => onInvest(id)}
                className="flex-1 py-2.5 text-center text-sm font-medium text-white bg-blue-600 hover:bg-blue-500 rounded-lg transition-colors"
              >
                Invertir Ahora
              </button>
            ) : (
              <Link
                to={`/investment/products/${id}`}
                className="flex-1 py-2.5 text-center text-sm font-medium text-white bg-blue-600 hover:bg-blue-500 rounded-lg transition-colors"
              >
                Invertir Ahora
              </Link>
            )
          ) : (
            <button
              disabled
              className="flex-1 py-2.5 text-center text-sm font-medium text-slate-500 bg-slate-800 rounded-lg cursor-not-allowed"
            >
              {status === 'closed' ? 'No Disponible' : 'Proximamente'}
            </button>
          )}
        </div>

        {status === 'limited' && (
          <div className="mt-3 flex items-center justify-center gap-2 text-xs text-amber-400">
            <Clock className="w-3 h-3" />
            <span>Cupo limitado - actua rapido</span>
          </div>
        )}
      </div>

      {/* Risk Warning */}
      <div className="px-4 pb-4">
        <div className="flex items-start gap-2 p-3 rounded-lg bg-amber-900/20 border border-amber-800/30">
          <AlertTriangle className="w-4 h-4 text-amber-500 flex-shrink-0 mt-0.5" />
          <p className="text-xs text-amber-400/80">
            El trading conlleva riesgos. Los rendimientos pasados no garantizan
            rendimientos futuros.
          </p>
        </div>
      </div>
    </div>
  );
};

export default ProductCard;
