/**
 * Rebalance Modal Component
 * Modal for reviewing and confirming portfolio rebalancing trades
 * Connects to GET /api/portfolio/:id/rebalance/calculate
 */

import React, { useEffect, useState } from 'react';
import {
  XMarkIcon,
  ArrowUpIcon,
  ArrowDownIcon,
  ExclamationTriangleIcon,
  CheckCircleIcon,
  ArrowPathIcon,
  BanknotesIcon,
  ReceiptPercentIcon,
} from '@heroicons/react/24/solid';
import {
  calculateRebalance,
  executeRebalance,
  type RebalanceCalculation,
  type RebalanceTrade,
} from '../../../services/portfolio.service';

interface RebalanceModalProps {
  isOpen: boolean;
  onClose: () => void;
  portfolioId: string;
  onSuccess?: () => void;
}

interface TradeRowProps {
  trade: RebalanceTrade;
}

const TradeRow: React.FC<TradeRowProps> = ({ trade }) => {
  const isBuy = trade.action === 'buy';

  return (
    <div
      className={`flex items-center justify-between p-4 rounded-lg ${
        isBuy
          ? 'bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800'
          : 'bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800'
      }`}
    >
      <div className="flex items-center gap-3">
        {isBuy ? (
          <div className="p-2 bg-green-100 dark:bg-green-900/40 rounded-full">
            <ArrowUpIcon className="w-4 h-4 text-green-600" />
          </div>
        ) : (
          <div className="p-2 bg-red-100 dark:bg-red-900/40 rounded-full">
            <ArrowDownIcon className="w-4 h-4 text-red-600" />
          </div>
        )}
        <div>
          <div className="flex items-center gap-2">
            <span className="font-bold text-gray-900 dark:text-white">
              {trade.asset}
            </span>
            {trade.priority === 'high' && (
              <span className="px-2 py-0.5 text-xs bg-red-100 dark:bg-red-900/40 text-red-600 rounded-full">
                Prioritario
              </span>
            )}
          </div>
          <p className="text-sm text-gray-500 dark:text-gray-400">
            {trade.currentPercent.toFixed(1)}% → {trade.targetPercent.toFixed(1)}%
            <span className="ml-2 text-gray-400">
              (Desv: {trade.deviation > 0 ? '+' : ''}{trade.deviation.toFixed(1)}%)
            </span>
          </p>
        </div>
      </div>
      <div className="text-right">
        <p className={`font-bold ${isBuy ? 'text-green-600' : 'text-red-600'}`}>
          {isBuy ? 'Comprar' : 'Vender'}
        </p>
        <p className="text-sm text-gray-900 dark:text-white">
          {trade.quantity.toLocaleString(undefined, { maximumFractionDigits: 8 })} unidades
        </p>
        <p className="text-sm text-gray-500 dark:text-gray-400">
          ~${trade.estimatedValue.toLocaleString(undefined, { minimumFractionDigits: 2 })}
        </p>
      </div>
    </div>
  );
};

export const RebalanceModal: React.FC<RebalanceModalProps> = ({
  isOpen,
  onClose,
  portfolioId,
  onSuccess,
}) => {
  const [calculation, setCalculation] = useState<RebalanceCalculation | null>(null);
  const [loading, setLoading] = useState(true);
  const [executing, setExecuting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

  useEffect(() => {
    if (isOpen && portfolioId) {
      loadCalculation();
    }
  }, [isOpen, portfolioId]);

  useEffect(() => {
    if (!isOpen) {
      setSuccess(false);
      setError(null);
    }
  }, [isOpen]);

  const loadCalculation = async () => {
    try {
      setLoading(true);
      setError(null);
      const data = await calculateRebalance(portfolioId);
      setCalculation(data);
    } catch (err) {
      console.error('Error loading rebalance calculation:', err);
      setError(err instanceof Error ? err.message : 'Error al calcular rebalanceo');
      // Use mock data for demo
      setCalculation(generateMockCalculation(portfolioId));
    } finally {
      setLoading(false);
    }
  };

  const generateMockCalculation = (pId: string): RebalanceCalculation => ({
    portfolioId: pId,
    currentValue: 25000,
    trades: [
      {
        asset: 'BTC',
        action: 'buy',
        quantity: 0.015,
        estimatedPrice: 45000,
        estimatedValue: 675,
        currentPercent: 35.2,
        targetPercent: 40,
        deviation: -4.8,
        priority: 'high',
      },
      {
        asset: 'ETH',
        action: 'sell',
        quantity: 0.25,
        estimatedPrice: 2400,
        estimatedValue: 600,
        currentPercent: 32.5,
        targetPercent: 30,
        deviation: 2.5,
        priority: 'medium',
      },
      {
        asset: 'SOL',
        action: 'buy',
        quantity: 2.5,
        estimatedPrice: 100,
        estimatedValue: 250,
        currentPercent: 12.3,
        targetPercent: 15,
        deviation: -2.7,
        priority: 'medium',
      },
    ],
    estimatedCost: 1525,
    estimatedFees: 7.62,
    totalTrades: 3,
    netChange: 75,
    summary: {
      totalBuy: 925,
      totalSell: 600,
      netFlow: 325,
      assetsToAdjust: 3,
      maxDeviation: 4.8,
      averageDeviation: 3.33,
    },
  });

  const handleExecute = async () => {
    if (!portfolioId) return;

    try {
      setExecuting(true);
      setError(null);
      await executeRebalance(portfolioId);
      setSuccess(true);
      setTimeout(() => {
        onSuccess?.();
        onClose();
      }, 2000);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error al ejecutar rebalanceo');
    } finally {
      setExecuting(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 overflow-y-auto">
      {/* Backdrop */}
      <div
        className="fixed inset-0 bg-black/50 backdrop-blur-sm"
        onClick={onClose}
      />

      {/* Modal */}
      <div className="relative min-h-screen flex items-center justify-center p-4">
        <div className="relative bg-white dark:bg-gray-800 rounded-2xl shadow-xl w-full max-w-2xl max-h-[90vh] overflow-hidden">
          {/* Header */}
          <div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-purple-100 dark:bg-purple-900/30 rounded-lg">
                <ArrowPathIcon className="w-6 h-6 text-purple-600" />
              </div>
              <div>
                <h2 className="text-xl font-bold text-gray-900 dark:text-white">
                  Rebalancear Portfolio
                </h2>
                <p className="text-sm text-gray-500 dark:text-gray-400">
                  Revisa los trades sugeridos antes de confirmar
                </p>
              </div>
            </div>
            <button
              onClick={onClose}
              className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 transition-colors"
            >
              <XMarkIcon className="w-6 h-6" />
            </button>
          </div>

          {/* Content */}
          <div className="p-6 overflow-y-auto max-h-[calc(90vh-200px)]">
            {loading ? (
              <div className="flex flex-col items-center justify-center py-12">
                <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-purple-600"></div>
                <p className="mt-4 text-gray-500 dark:text-gray-400">
                  Calculando trades optimos...
                </p>
              </div>
            ) : success ? (
              <div className="flex flex-col items-center justify-center py-12">
                <div className="p-4 bg-green-100 dark:bg-green-900/30 rounded-full">
                  <CheckCircleIcon className="w-16 h-16 text-green-500" />
                </div>
                <h3 className="mt-4 text-xl font-bold text-gray-900 dark:text-white">
                  Rebalanceo Exitoso
                </h3>
                <p className="mt-2 text-gray-500 dark:text-gray-400">
                  Tu portfolio ha sido rebalanceado correctamente
                </p>
              </div>
            ) : error && !calculation ? (
              <div className="flex flex-col items-center justify-center py-12">
                <ExclamationTriangleIcon className="w-16 h-16 text-red-500" />
                <p className="mt-4 text-red-500">{error}</p>
                <button
                  onClick={loadCalculation}
                  className="mt-4 px-4 py-2 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
                >
                  Reintentar
                </button>
              </div>
            ) : calculation ? (
              <>
                {/* Summary Stats */}
                <div className="grid grid-cols-3 gap-4 mb-6">
                  <div className="p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg text-center">
                    <BanknotesIcon className="w-6 h-6 text-blue-500 mx-auto mb-2" />
                    <p className="text-xs text-gray-500 dark:text-gray-400">
                      Valor Portfolio
                    </p>
                    <p className="text-lg font-bold text-gray-900 dark:text-white">
                      ${calculation.currentValue.toLocaleString()}
                    </p>
                  </div>
                  <div className="p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg text-center">
                    <ArrowPathIcon className="w-6 h-6 text-purple-500 mx-auto mb-2" />
                    <p className="text-xs text-gray-500 dark:text-gray-400">
                      Total Trades
                    </p>
                    <p className="text-lg font-bold text-gray-900 dark:text-white">
                      {calculation.totalTrades}
                    </p>
                  </div>
                  <div className="p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg text-center">
                    <ReceiptPercentIcon className="w-6 h-6 text-yellow-500 mx-auto mb-2" />
                    <p className="text-xs text-gray-500 dark:text-gray-400">
                      Comisiones Est.
                    </p>
                    <p className="text-lg font-bold text-gray-900 dark:text-white">
                      ${calculation.estimatedFees.toFixed(2)}
                    </p>
                  </div>
                </div>

                {/* Trade Summary */}
                <div className="mb-6 p-4 bg-purple-50 dark:bg-purple-900/20 rounded-lg border border-purple-200 dark:border-purple-800">
                  <h4 className="font-semibold text-gray-900 dark:text-white mb-3">
                    Resumen de Transacciones
                  </h4>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="flex justify-between">
                      <span className="text-gray-500 dark:text-gray-400">Total Compras:</span>
                      <span className="font-medium text-green-600">
                        +${calculation.summary.totalBuy.toLocaleString()}
                      </span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-500 dark:text-gray-400">Total Ventas:</span>
                      <span className="font-medium text-red-600">
                        -${calculation.summary.totalSell.toLocaleString()}
                      </span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-500 dark:text-gray-400">Flujo Neto:</span>
                      <span className={`font-medium ${calculation.summary.netFlow >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                        {calculation.summary.netFlow >= 0 ? '+' : ''}${calculation.summary.netFlow.toLocaleString()}
                      </span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-500 dark:text-gray-400">Desv. Maxima:</span>
                      <span className="font-medium text-gray-900 dark:text-white">
                        {calculation.summary.maxDeviation.toFixed(1)}%
                      </span>
                    </div>
                  </div>
                </div>

                {/* Trades List */}
                <div className="space-y-3">
                  <h4 className="font-semibold text-gray-900 dark:text-white">
                    Trades Sugeridos
                  </h4>
                  {calculation.trades.map((trade, index) => (
                    <TradeRow key={index} trade={trade} />
                  ))}
                </div>

                {/* Cost Warning */}
                <div className="mt-6 p-4 bg-yellow-50 dark:bg-yellow-900/20 rounded-lg border border-yellow-200 dark:border-yellow-800">
                  <div className="flex items-start gap-3">
                    <ExclamationTriangleIcon className="w-5 h-5 text-yellow-500 flex-shrink-0 mt-0.5" />
                    <div>
                      <p className="font-medium text-yellow-800 dark:text-yellow-200">
                        Costos Estimados
                      </p>
                      <p className="text-sm text-yellow-700 dark:text-yellow-300 mt-1">
                        Esta operacion generara comisiones estimadas de{' '}
                        <strong>${calculation.estimatedFees.toFixed(2)}</strong>.
                        Los precios finales pueden variar segun el mercado al momento de ejecucion.
                      </p>
                    </div>
                  </div>
                </div>

                {/* Error message */}
                {error && (
                  <div className="mt-4 p-4 bg-red-50 dark:bg-red-900/20 rounded-lg border border-red-200 dark:border-red-800">
                    <p className="text-red-600 dark:text-red-400">{error}</p>
                  </div>
                )}
              </>
            ) : null}
          </div>

          {/* Footer */}
          {!loading && !success && calculation && (
            <div className="p-6 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50">
              <div className="flex gap-4">
                <button
                  onClick={onClose}
                  disabled={executing}
                  className="flex-1 py-3 px-4 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 font-medium rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors disabled:opacity-50"
                >
                  Cancelar
                </button>
                <button
                  onClick={handleExecute}
                  disabled={executing}
                  className="flex-1 py-3 px-4 bg-purple-600 hover:bg-purple-700 text-white font-medium rounded-lg transition-colors disabled:opacity-50 flex items-center justify-center gap-2"
                >
                  {executing ? (
                    <>
                      <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
                      Ejecutando...
                    </>
                  ) : (
                    <>
                      <CheckCircleIcon className="w-5 h-5" />
                      Confirmar Rebalanceo
                    </>
                  )}
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default RebalanceModal;
