/**
 * ProductComparisonTable Component
 * Side-by-side comparison of investment products
 * OQI-004: Cuentas de Inversion
 */

import React, { useState } from 'react';
import {
  Check,
  X,
  ChevronDown,
  ChevronUp,
  Star,
  TrendingUp,
  Shield,
  DollarSign,
  Percent,
  Clock,
  Users,
  Zap,
  Info,
} from 'lucide-react';

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

export interface ProductFeature {
  name: string;
  description?: string;
  values: Record<string, string | number | boolean>;
}

export interface InvestmentProduct {
  id: string;
  name: string;
  type: 'atlas' | 'orion' | 'nova' | 'custom';
  description: string;
  targetReturn: { min: number; max: number };
  maxDrawdown: number;
  managementFee: number;
  performanceFee: number;
  minCapital: number;
  lockPeriod: number;
  riskLevel: 'low' | 'medium' | 'high';
  strategies: string[];
  features: string[];
  isPopular?: boolean;
  historicalReturn?: number;
  activeAccounts?: number;
}

interface ProductComparisonTableProps {
  products: InvestmentProduct[];
  selectedProductId?: string;
  onSelectProduct?: (productId: string) => void;
  onViewDetails?: (productId: string) => void;
  compact?: boolean;
}

// ============================================================================
// Helper Functions
// ============================================================================

const getProductColor = (type: InvestmentProduct['type']) => {
  switch (type) {
    case 'atlas':
      return { bg: 'bg-blue-500', text: 'text-blue-400', border: 'border-blue-500', gradient: 'from-blue-500 to-blue-600' };
    case 'orion':
      return { bg: 'bg-purple-500', text: 'text-purple-400', border: 'border-purple-500', gradient: 'from-purple-500 to-purple-600' };
    case 'nova':
      return { bg: 'bg-amber-500', text: 'text-amber-400', border: 'border-amber-500', gradient: 'from-amber-500 to-amber-600' };
    default:
      return { bg: 'bg-slate-500', text: 'text-slate-400', border: 'border-slate-500', gradient: 'from-slate-500 to-slate-600' };
  }
};

const getRiskBadge = (riskLevel: InvestmentProduct['riskLevel']) => {
  switch (riskLevel) {
    case 'low':
      return { label: 'Low Risk', className: 'bg-emerald-500/20 text-emerald-400' };
    case 'medium':
      return { label: 'Medium Risk', className: 'bg-yellow-500/20 text-yellow-400' };
    case 'high':
      return { label: 'High Risk', className: 'bg-red-500/20 text-red-400' };
    default:
      return { label: riskLevel, className: 'bg-slate-500/20 text-slate-400' };
  }
};

const formatCurrency = (value: number) => {
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
  }).format(value);
};

// ============================================================================
// Component
// ============================================================================

export const ProductComparisonTable: React.FC<ProductComparisonTableProps> = ({
  products,
  selectedProductId,
  onSelectProduct,
  onViewDetails,
  compact = false,
}) => {
  const [expandedSection, setExpandedSection] = useState<string | null>('returns');
  const [hoveredProduct, setHoveredProduct] = useState<string | null>(null);

  const toggleSection = (section: string) => {
    setExpandedSection(expandedSection === section ? null : section);
  };

  const comparisonSections = [
    {
      id: 'returns',
      label: 'Returns & Performance',
      icon: TrendingUp,
      rows: [
        { label: 'Target Return', key: 'targetReturn', format: (p: InvestmentProduct) => `${p.targetReturn.min}% - ${p.targetReturn.max}%` },
        { label: 'Historical Return', key: 'historicalReturn', format: (p: InvestmentProduct) => p.historicalReturn ? `${p.historicalReturn.toFixed(1)}%` : 'N/A' },
        { label: 'Max Drawdown', key: 'maxDrawdown', format: (p: InvestmentProduct) => `${p.maxDrawdown}%` },
      ],
    },
    {
      id: 'fees',
      label: 'Fees & Costs',
      icon: DollarSign,
      rows: [
        { label: 'Management Fee', key: 'managementFee', format: (p: InvestmentProduct) => `${p.managementFee}%/year` },
        { label: 'Performance Fee', key: 'performanceFee', format: (p: InvestmentProduct) => `${p.performanceFee}%` },
        { label: 'Min Capital', key: 'minCapital', format: (p: InvestmentProduct) => formatCurrency(p.minCapital) },
      ],
    },
    {
      id: 'terms',
      label: 'Terms & Conditions',
      icon: Clock,
      rows: [
        { label: 'Lock Period', key: 'lockPeriod', format: (p: InvestmentProduct) => `${p.lockPeriod} months` },
        { label: 'Risk Level', key: 'riskLevel', format: (p: InvestmentProduct) => getRiskBadge(p.riskLevel).label },
        { label: 'Active Accounts', key: 'activeAccounts', format: (p: InvestmentProduct) => p.activeAccounts?.toLocaleString() || 'N/A' },
      ],
    },
  ];

  if (compact) {
    return (
      <div className="overflow-x-auto">
        <table className="w-full min-w-[600px]">
          <thead>
            <tr className="border-b border-slate-700">
              <th className="text-left py-3 px-4 text-sm font-medium text-slate-400">Product</th>
              <th className="text-center py-3 px-4 text-sm font-medium text-slate-400">Target Return</th>
              <th className="text-center py-3 px-4 text-sm font-medium text-slate-400">Min Capital</th>
              <th className="text-center py-3 px-4 text-sm font-medium text-slate-400">Risk</th>
              <th className="text-center py-3 px-4 text-sm font-medium text-slate-400">Action</th>
            </tr>
          </thead>
          <tbody>
            {products.map((product) => {
              const colors = getProductColor(product.type);
              const risk = getRiskBadge(product.riskLevel);
              const isSelected = selectedProductId === product.id;

              return (
                <tr
                  key={product.id}
                  className={`border-b border-slate-700/50 hover:bg-slate-800/50 transition-colors ${isSelected ? 'bg-slate-800/50' : ''}`}
                >
                  <td className="py-3 px-4">
                    <div className="flex items-center gap-3">
                      <div className={`w-8 h-8 rounded-lg bg-gradient-to-br ${colors.gradient} flex items-center justify-center`}>
                        <Zap className="w-4 h-4 text-white" />
                      </div>
                      <div>
                        <div className="font-medium text-white flex items-center gap-2">
                          {product.name}
                          {product.isPopular && <Star className="w-3.5 h-3.5 text-amber-400 fill-amber-400" />}
                        </div>
                        <div className="text-xs text-slate-500">{product.strategies.length} strategies</div>
                      </div>
                    </div>
                  </td>
                  <td className="py-3 px-4 text-center">
                    <span className="text-emerald-400 font-medium">
                      {product.targetReturn.min}%-{product.targetReturn.max}%
                    </span>
                  </td>
                  <td className="py-3 px-4 text-center text-white">
                    {formatCurrency(product.minCapital)}
                  </td>
                  <td className="py-3 px-4 text-center">
                    <span className={`px-2 py-0.5 rounded text-xs font-medium ${risk.className}`}>
                      {risk.label}
                    </span>
                  </td>
                  <td className="py-3 px-4 text-center">
                    <button
                      onClick={() => onSelectProduct?.(product.id)}
                      className={`px-4 py-1.5 rounded-lg text-sm font-medium transition-colors ${
                        isSelected
                          ? 'bg-emerald-500 text-white'
                          : 'bg-slate-700 text-white hover:bg-slate-600'
                      }`}
                    >
                      {isSelected ? 'Selected' : 'Select'}
                    </button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    );
  }

  return (
    <div className="bg-slate-800/50 rounded-xl border border-slate-700 overflow-hidden">
      {/* Header Row - Product Names */}
      <div className="grid grid-cols-[200px_repeat(auto-fit,minmax(180px,1fr))] border-b border-slate-700">
        <div className="p-4 bg-slate-900/50">
          <span className="text-sm font-medium text-slate-400">Compare Products</span>
        </div>
        {products.map((product) => {
          const colors = getProductColor(product.type);
          const isSelected = selectedProductId === product.id;
          const isHovered = hoveredProduct === product.id;

          return (
            <div
              key={product.id}
              onMouseEnter={() => setHoveredProduct(product.id)}
              onMouseLeave={() => setHoveredProduct(null)}
              className={`p-4 text-center border-l border-slate-700 transition-colors ${
                isSelected ? 'bg-slate-700/50' : isHovered ? 'bg-slate-800' : ''
              }`}
            >
              <div className={`w-12 h-12 mx-auto rounded-xl bg-gradient-to-br ${colors.gradient} flex items-center justify-center mb-2 shadow-lg`}>
                <Zap className="w-6 h-6 text-white" />
              </div>
              <div className="font-semibold text-white flex items-center justify-center gap-1">
                {product.name}
                {product.isPopular && <Star className="w-4 h-4 text-amber-400 fill-amber-400" />}
              </div>
              <div className="text-xs text-slate-500 mt-1">{product.description}</div>
            </div>
          );
        })}
      </div>

      {/* Comparison Sections */}
      {comparisonSections.map((section) => {
        const Icon = section.icon;
        const isExpanded = expandedSection === section.id;

        return (
          <div key={section.id} className="border-b border-slate-700 last:border-b-0">
            {/* Section Header */}
            <button
              onClick={() => toggleSection(section.id)}
              className="w-full grid grid-cols-[200px_1fr] hover:bg-slate-800/50 transition-colors"
            >
              <div className="p-3 flex items-center gap-2 text-left">
                <Icon className="w-4 h-4 text-slate-400" />
                <span className="text-sm font-medium text-slate-300">{section.label}</span>
                {isExpanded ? (
                  <ChevronUp className="w-4 h-4 text-slate-500 ml-auto" />
                ) : (
                  <ChevronDown className="w-4 h-4 text-slate-500 ml-auto" />
                )}
              </div>
              <div className="border-l border-slate-700" />
            </button>

            {/* Section Rows */}
            {isExpanded && section.rows.map((row, rowIdx) => (
              <div
                key={row.key}
                className={`grid grid-cols-[200px_repeat(auto-fit,minmax(180px,1fr))] ${
                  rowIdx < section.rows.length - 1 ? 'border-b border-slate-700/50' : ''
                }`}
              >
                <div className="p-3 pl-10 bg-slate-900/30">
                  <span className="text-sm text-slate-400">{row.label}</span>
                </div>
                {products.map((product) => {
                  const isSelected = selectedProductId === product.id;
                  const isHovered = hoveredProduct === product.id;

                  return (
                    <div
                      key={product.id}
                      className={`p-3 text-center border-l border-slate-700 transition-colors ${
                        isSelected ? 'bg-slate-700/30' : isHovered ? 'bg-slate-800/30' : ''
                      }`}
                    >
                      <span className="text-sm text-white">{row.format(product)}</span>
                    </div>
                  );
                })}
              </div>
            ))}
          </div>
        );
      })}

      {/* Strategies Section */}
      <div className="border-b border-slate-700">
        <button
          onClick={() => toggleSection('strategies')}
          className="w-full grid grid-cols-[200px_1fr] hover:bg-slate-800/50 transition-colors"
        >
          <div className="p-3 flex items-center gap-2 text-left">
            <Shield className="w-4 h-4 text-slate-400" />
            <span className="text-sm font-medium text-slate-300">Trading Strategies</span>
            {expandedSection === 'strategies' ? (
              <ChevronUp className="w-4 h-4 text-slate-500 ml-auto" />
            ) : (
              <ChevronDown className="w-4 h-4 text-slate-500 ml-auto" />
            )}
          </div>
          <div className="border-l border-slate-700" />
        </button>

        {expandedSection === 'strategies' && (
          <div className="grid grid-cols-[200px_repeat(auto-fit,minmax(180px,1fr))]">
            <div className="p-3 pl-10 bg-slate-900/30">
              <span className="text-sm text-slate-400">Included</span>
            </div>
            {products.map((product) => {
              const isSelected = selectedProductId === product.id;

              return (
                <div
                  key={product.id}
                  className={`p-3 border-l border-slate-700 ${isSelected ? 'bg-slate-700/30' : ''}`}
                >
                  <div className="flex flex-wrap gap-1 justify-center">
                    {product.strategies.map((strategy) => (
                      <span
                        key={strategy}
                        className="px-2 py-0.5 bg-slate-700 text-xs text-slate-300 rounded"
                      >
                        {strategy}
                      </span>
                    ))}
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* Action Row */}
      <div className="grid grid-cols-[200px_repeat(auto-fit,minmax(180px,1fr))] bg-slate-900/30">
        <div className="p-4" />
        {products.map((product) => {
          const isSelected = selectedProductId === product.id;
          const colors = getProductColor(product.type);

          return (
            <div key={product.id} className="p-4 border-l border-slate-700 flex flex-col gap-2">
              <button
                onClick={() => onSelectProduct?.(product.id)}
                className={`w-full py-2 rounded-lg font-medium transition-colors ${
                  isSelected
                    ? 'bg-emerald-500 text-white'
                    : `bg-gradient-to-r ${colors.gradient} text-white hover:opacity-90`
                }`}
              >
                {isSelected ? 'Selected' : 'Choose Plan'}
              </button>
              {onViewDetails && (
                <button
                  onClick={() => onViewDetails(product.id)}
                  className="w-full py-2 text-sm text-slate-400 hover:text-white transition-colors flex items-center justify-center gap-1"
                >
                  <Info className="w-3.5 h-3.5" /> View Details
                </button>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
};

export default ProductComparisonTable;
