/**
 * Rebalance Card Component
 * Displays rebalancing recommendations
 */

import React from 'react';
import {
  ArrowUpIcon,
  ArrowDownIcon,
  MinusIcon,
  ExclamationTriangleIcon,
} from '@heroicons/react/24/solid';
import type { RebalanceRecommendation } from '../../../services/portfolio.service';

interface RebalanceCardProps {
  recommendations: RebalanceRecommendation[];
  onExecute?: () => void;
  isExecuting?: boolean;
}

export const RebalanceCard: React.FC<RebalanceCardProps> = ({
  recommendations,
  onExecute,
  isExecuting = false,
}) => {
  const hasRecommendations = recommendations.some((r) => r.action !== 'hold');
  const highPriorityCount = recommendations.filter((r) => r.priority === 'high').length;

  return (
    <div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-3">
          <div className="p-2 bg-purple-100 dark:bg-purple-900/30 rounded-lg">
            <span className="text-2xl">⚖️</span>
          </div>
          <div>
            <h3 className="font-bold text-gray-900 dark:text-white">Rebalanceo</h3>
            <p className="text-sm text-gray-500 dark:text-gray-400">
              {hasRecommendations
                ? `${highPriorityCount} acción(es) prioritaria(s)`
                : 'Portfolio balanceado'}
            </p>
          </div>
        </div>
        {hasRecommendations && onExecute && (
          <button
            onClick={onExecute}
            disabled={isExecuting}
            className="px-4 py-2 bg-purple-600 hover:bg-purple-700 disabled:bg-purple-400 text-white font-medium rounded-lg transition-colors flex items-center gap-2"
          >
            {isExecuting ? (
              <>
                <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                Ejecutando...
              </>
            ) : (
              'Ejecutar Rebalanceo'
            )}
          </button>
        )}
      </div>

      {!hasRecommendations ? (
        <div className="text-center py-8">
          <span className="text-4xl">✅</span>
          <p className="mt-2 text-gray-600 dark:text-gray-400">
            Tu portfolio está bien balanceado
          </p>
          <p className="text-sm text-gray-500 dark:text-gray-500 mt-1">
            No se requieren ajustes en este momento
          </p>
        </div>
      ) : (
        <div className="space-y-3">
          {recommendations
            .filter((r) => r.action !== 'hold')
            .sort((a, b) => {
              const priorityOrder = { high: 0, medium: 1, low: 2 };
              return priorityOrder[a.priority] - priorityOrder[b.priority];
            })
            .map((rec, index) => (
              <div
                key={index}
                className={`flex items-center justify-between p-4 rounded-lg ${
                  rec.priority === 'high'
                    ? 'bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800'
                    : rec.priority === 'medium'
                    ? 'bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800'
                    : 'bg-gray-50 dark:bg-gray-700/50 border border-gray-200 dark:border-gray-600'
                }`}
              >
                <div className="flex items-center gap-3">
                  {rec.action === 'buy' ? (
                    <div className="p-2 bg-green-100 dark:bg-green-900/30 rounded-full">
                      <ArrowUpIcon className="w-4 h-4 text-green-600" />
                    </div>
                  ) : rec.action === 'sell' ? (
                    <div className="p-2 bg-red-100 dark:bg-red-900/30 rounded-full">
                      <ArrowDownIcon className="w-4 h-4 text-red-600" />
                    </div>
                  ) : (
                    <div className="p-2 bg-gray-100 dark:bg-gray-700 rounded-full">
                      <MinusIcon className="w-4 h-4 text-gray-600" />
                    </div>
                  )}
                  <div>
                    <div className="flex items-center gap-2">
                      <span className="font-medium text-gray-900 dark:text-white">
                        {rec.asset}
                      </span>
                      {rec.priority === 'high' && (
                        <ExclamationTriangleIcon className="w-4 h-4 text-red-500" />
                      )}
                    </div>
                    <p className="text-sm text-gray-500 dark:text-gray-400">
                      {rec.currentPercent.toFixed(1)}% → {rec.targetPercent.toFixed(1)}%
                    </p>
                  </div>
                </div>
                <div className="text-right">
                  <p
                    className={`font-medium ${
                      rec.action === 'buy' ? 'text-green-600' : 'text-red-600'
                    }`}
                  >
                    {rec.action === 'buy' ? 'Comprar' : 'Vender'}
                  </p>
                  <p className="text-sm text-gray-500 dark:text-gray-400">
                    ~${rec.amountUSD.toLocaleString(undefined, { maximumFractionDigits: 0 })}
                  </p>
                </div>
              </div>
            ))}
        </div>
      )}

      {hasRecommendations && (
        <div className="mt-4 pt-4 border-t border-gray-200 dark:border-gray-700">
          <p className="text-xs text-gray-500 dark:text-gray-400">
            💡 Se recomienda rebalancear cuando la desviación supera el 5% del objetivo
          </p>
        </div>
      )}
    </div>
  );
};

export default RebalanceCard;
