/**
 * Rebalancing Panel Component
 * Enhanced rebalancing UI with history, drift settings,
 * target vs current comparison, and one-click suggestions
 */

import React, { useState, useEffect, useMemo } from 'react';
import {
  ArrowsRightLeftIcon,
  ClockIcon,
  CogIcon,
  ArrowUpIcon,
  ArrowDownIcon,
  CheckCircleIcon,
  ExclamationTriangleIcon,
  CalendarIcon,
  ChartBarIcon,
  AdjustmentsHorizontalIcon,
} from '@heroicons/react/24/solid';
import type { PortfolioAllocation, RebalanceRecommendation } from '../../../services/portfolio.service';

interface RebalancingPanelProps {
  portfolioId: string;
  allocations: PortfolioAllocation[];
  recommendations?: RebalanceRecommendation[];
  onRebalance?: () => void;
  isExecuting?: boolean;
  lastRebalanced?: string | null;
}

interface RebalanceHistoryItem {
  id: string;
  date: string;
  tradesCount: number;
  totalVolume: number;
  driftBefore: number;
  driftAfter: number;
  status: 'completed' | 'partial' | 'failed';
}

interface DriftSettings {
  threshold: number;
  autoRebalance: boolean;
  frequency: 'manual' | 'weekly' | 'monthly' | 'quarterly';
  notifyOnDrift: boolean;
}

// Mock history data
const generateMockHistory = (): RebalanceHistoryItem[] => {
  return [
    {
      id: '1',
      date: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(),
      tradesCount: 4,
      totalVolume: 2500,
      driftBefore: 8.5,
      driftAfter: 0.3,
      status: 'completed',
    },
    {
      id: '2',
      date: new Date(Date.now() - 60 * 24 * 60 * 60 * 1000).toISOString(),
      tradesCount: 3,
      totalVolume: 1800,
      driftBefore: 6.2,
      driftAfter: 0.5,
      status: 'completed',
    },
    {
      id: '3',
      date: new Date(Date.now() - 90 * 24 * 60 * 60 * 1000).toISOString(),
      tradesCount: 5,
      totalVolume: 3200,
      driftBefore: 12.1,
      driftAfter: 0.2,
      status: 'completed',
    },
    {
      id: '4',
      date: new Date(Date.now() - 120 * 24 * 60 * 60 * 1000).toISOString(),
      tradesCount: 2,
      totalVolume: 950,
      driftBefore: 5.8,
      driftAfter: 1.2,
      status: 'partial',
    },
  ];
};

// Allocation comparison bar component
interface AllocationBarProps {
  asset: string;
  current: number;
  target: number;
  color: string;
}

const AllocationBar: React.FC<AllocationBarProps> = ({ asset, current, target, color }) => {
  const deviation = current - target;
  const maxPercent = Math.max(current, target, 50);

  return (
    <div className="space-y-1">
      <div className="flex items-center justify-between text-sm">
        <span className="font-medium text-gray-900 dark:text-white">{asset}</span>
        <div className="flex items-center gap-2">
          <span className="text-gray-500 dark:text-gray-400">
            {current.toFixed(1)}% / {target.toFixed(1)}%
          </span>
          <span
            className={`text-xs font-medium px-1.5 py-0.5 rounded ${
              Math.abs(deviation) > 5
                ? 'bg-red-100 dark:bg-red-900/30 text-red-600'
                : Math.abs(deviation) > 2
                ? 'bg-yellow-100 dark:bg-yellow-900/30 text-yellow-600'
                : 'bg-green-100 dark:bg-green-900/30 text-green-600'
            }`}
          >
            {deviation > 0 ? '+' : ''}{deviation.toFixed(1)}%
          </span>
        </div>
      </div>
      <div className="relative h-4 bg-gray-100 dark:bg-gray-700 rounded-full overflow-hidden">
        {/* Current allocation bar */}
        <div
          className="absolute top-0 left-0 h-full rounded-full transition-all duration-300"
          style={{
            width: `${(current / maxPercent) * 100}%`,
            backgroundColor: color,
          }}
        />
        {/* Target marker */}
        <div
          className="absolute top-0 h-full w-0.5 bg-gray-900 dark:bg-white"
          style={{ left: `${(target / maxPercent) * 100}%` }}
        />
      </div>
    </div>
  );
};

// Asset colors
const ASSET_COLORS: Record<string, string> = {
  BTC: '#F7931A',
  ETH: '#627EEA',
  USDT: '#26A17B',
  USDC: '#2775CA',
  SOL: '#9945FF',
  LINK: '#2A5ADA',
  AVAX: '#E84142',
  ADA: '#0033AD',
  DOT: '#E6007A',
  MATIC: '#8247E5',
};

const DEFAULT_COLOR = '#6366F1';

export const RebalancingPanel: React.FC<RebalancingPanelProps> = ({
  portfolioId,
  allocations,
  recommendations = [],
  onRebalance,
  isExecuting = false,
  lastRebalanced,
}) => {
  const [activeTab, setActiveTab] = useState<'overview' | 'history' | 'settings'>('overview');
  const [history, setHistory] = useState<RebalanceHistoryItem[]>([]);
  const [loadingHistory, setLoadingHistory] = useState(false);
  const [settings, setSettings] = useState<DriftSettings>({
    threshold: 5,
    autoRebalance: false,
    frequency: 'manual',
    notifyOnDrift: true,
  });

  // Load history on mount
  useEffect(() => {
    if (activeTab === 'history') {
      setLoadingHistory(true);
      // Simulate API call
      setTimeout(() => {
        setHistory(generateMockHistory());
        setLoadingHistory(false);
      }, 500);
    }
  }, [activeTab]);

  // Calculate max drift
  const maxDrift = useMemo(() => {
    return Math.max(...allocations.map((a) => Math.abs(a.deviation)));
  }, [allocations]);

  // Calculate days since last rebalance
  const daysSinceRebalance = useMemo(() => {
    if (!lastRebalanced) return null;
    const diff = Date.now() - new Date(lastRebalanced).getTime();
    return Math.floor(diff / (1000 * 60 * 60 * 24));
  }, [lastRebalanced]);

  // Check if rebalance is needed based on settings
  const needsRebalance = maxDrift > settings.threshold;

  // Active recommendations count
  const activeRecommendations = recommendations.filter((r) => r.action !== 'hold');

  // Calculate total trade volume
  const totalTradeVolume = activeRecommendations.reduce((sum, r) => sum + r.amountUSD, 0);

  return (
    <div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg">
      {/* Header with Tabs */}
      <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">
            <ArrowsRightLeftIcon className="w-6 h-6 text-purple-600" />
          </div>
          <div>
            <h3 className="font-bold text-gray-900 dark:text-white">Sistema de Rebalanceo</h3>
            <p className="text-sm text-gray-500 dark:text-gray-400">
              {needsRebalance
                ? `Drift maximo: ${maxDrift.toFixed(1)}% (umbral: ${settings.threshold}%)`
                : 'Portfolio balanceado'}
            </p>
          </div>
        </div>

        {/* Tabs */}
        <div className="flex gap-1 bg-gray-100 dark:bg-gray-700 rounded-lg p-1">
          <button
            onClick={() => setActiveTab('overview')}
            className={`px-3 py-1.5 text-sm font-medium rounded-md transition-colors ${
              activeTab === 'overview'
                ? 'bg-white dark:bg-gray-600 text-gray-900 dark:text-white shadow-sm'
                : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white'
            }`}
          >
            <ChartBarIcon className="w-4 h-4 inline mr-1" />
            Vista
          </button>
          <button
            onClick={() => setActiveTab('history')}
            className={`px-3 py-1.5 text-sm font-medium rounded-md transition-colors ${
              activeTab === 'history'
                ? 'bg-white dark:bg-gray-600 text-gray-900 dark:text-white shadow-sm'
                : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white'
            }`}
          >
            <ClockIcon className="w-4 h-4 inline mr-1" />
            Historial
          </button>
          <button
            onClick={() => setActiveTab('settings')}
            className={`px-3 py-1.5 text-sm font-medium rounded-md transition-colors ${
              activeTab === 'settings'
                ? 'bg-white dark:bg-gray-600 text-gray-900 dark:text-white shadow-sm'
                : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white'
            }`}
          >
            <CogIcon className="w-4 h-4 inline mr-1" />
            Config
          </button>
        </div>
      </div>

      {/* Content */}
      <div className="p-6">
        {/* Overview Tab */}
        {activeTab === 'overview' && (
          <>
            {/* Status Cards */}
            <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">
                <p className="text-xs text-gray-500 dark:text-gray-400 mb-1">Drift Maximo</p>
                <p className={`text-2xl font-bold ${
                  maxDrift > settings.threshold ? 'text-red-500' :
                  maxDrift > settings.threshold * 0.5 ? 'text-yellow-500' : 'text-green-500'
                }`}>
                  {maxDrift.toFixed(1)}%
                </p>
              </div>
              <div className="p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg text-center">
                <p className="text-xs text-gray-500 dark:text-gray-400 mb-1">Operaciones</p>
                <p className="text-2xl font-bold text-gray-900 dark:text-white">
                  {activeRecommendations.length}
                </p>
              </div>
              <div className="p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg text-center">
                <p className="text-xs text-gray-500 dark:text-gray-400 mb-1">Volumen Est.</p>
                <p className="text-2xl font-bold text-gray-900 dark:text-white">
                  ${totalTradeVolume.toLocaleString(undefined, { maximumFractionDigits: 0 })}
                </p>
              </div>
            </div>

            {/* Allocation Comparison */}
            <div className="mb-6">
              <h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-4">
                Actual vs Objetivo
              </h4>
              <div className="space-y-4">
                {allocations.map((alloc) => (
                  <AllocationBar
                    key={alloc.asset}
                    asset={alloc.asset}
                    current={alloc.currentPercent}
                    target={alloc.targetPercent}
                    color={ASSET_COLORS[alloc.asset] || DEFAULT_COLOR}
                  />
                ))}
              </div>
            </div>

            {/* Recommendations */}
            {activeRecommendations.length > 0 ? (
              <div className="mb-6">
                <h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3">
                  Acciones Sugeridas
                </h4>
                <div className="space-y-2">
                  {activeRecommendations
                    .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-3 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-1.5 bg-green-100 dark:bg-green-900/30 rounded-full">
                              <ArrowUpIcon className="w-4 h-4 text-green-600" />
                            </div>
                          ) : (
                            <div className="p-1.5 bg-red-100 dark:bg-red-900/30 rounded-full">
                              <ArrowDownIcon className="w-4 h-4 text-red-600" />
                            </div>
                          )}
                          <div>
                            <span className="font-medium text-gray-900 dark:text-white">
                              {rec.asset}
                            </span>
                            <span className="text-sm text-gray-500 dark:text-gray-400 ml-2">
                              {rec.currentPercent.toFixed(1)}% &rarr; {rec.targetPercent.toFixed(1)}%
                            </span>
                          </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>
              </div>
            ) : (
              <div className="mb-6 text-center py-8 bg-green-50 dark:bg-green-900/20 rounded-lg">
                <CheckCircleIcon className="w-12 h-12 text-green-500 mx-auto mb-2" />
                <p className="font-medium text-green-700 dark:text-green-300">
                  Portfolio Balanceado
                </p>
                <p className="text-sm text-green-600 dark:text-green-400 mt-1">
                  No se requieren ajustes en este momento
                </p>
              </div>
            )}

            {/* Rebalance Button */}
            {activeRecommendations.length > 0 && onRebalance && (
              <button
                onClick={onRebalance}
                disabled={isExecuting}
                className="w-full py-3 bg-purple-600 hover:bg-purple-700 disabled:bg-purple-400 text-white font-medium rounded-lg transition-colors flex items-center justify-center gap-2"
              >
                {isExecuting ? (
                  <>
                    <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
                    Ejecutando...
                  </>
                ) : (
                  <>
                    <ArrowsRightLeftIcon className="w-5 h-5" />
                    Ejecutar Rebalanceo
                  </>
                )}
              </button>
            )}

            {/* Last Rebalance Info */}
            {lastRebalanced && (
              <div className="mt-4 pt-4 border-t border-gray-200 dark:border-gray-700 text-sm text-gray-500 dark:text-gray-400">
                <div className="flex items-center gap-2">
                  <CalendarIcon className="w-4 h-4" />
                  Ultimo rebalanceo: {new Date(lastRebalanced).toLocaleDateString()}
                  {daysSinceRebalance !== null && (
                    <span className="text-gray-400">
                      (hace {daysSinceRebalance} dias)
                    </span>
                  )}
                </div>
              </div>
            )}
          </>
        )}

        {/* History Tab */}
        {activeTab === 'history' && (
          <>
            {loadingHistory ? (
              <div className="flex items-center justify-center py-12">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600"></div>
              </div>
            ) : history.length > 0 ? (
              <div className="space-y-4">
                {history.map((item) => (
                  <div
                    key={item.id}
                    className="p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg"
                  >
                    <div className="flex items-center justify-between mb-3">
                      <div className="flex items-center gap-2">
                        <span className={`p-1 rounded-full ${
                          item.status === 'completed'
                            ? 'bg-green-100 dark:bg-green-900/30'
                            : item.status === 'partial'
                            ? 'bg-yellow-100 dark:bg-yellow-900/30'
                            : 'bg-red-100 dark:bg-red-900/30'
                        }`}>
                          {item.status === 'completed' ? (
                            <CheckCircleIcon className="w-4 h-4 text-green-500" />
                          ) : (
                            <ExclamationTriangleIcon className={`w-4 h-4 ${
                              item.status === 'partial' ? 'text-yellow-500' : 'text-red-500'
                            }`} />
                          )}
                        </span>
                        <span className="font-medium text-gray-900 dark:text-white">
                          {new Date(item.date).toLocaleDateString()}
                        </span>
                      </div>
                      <span className={`text-xs px-2 py-1 rounded-full ${
                        item.status === 'completed'
                          ? 'bg-green-100 dark:bg-green-900/30 text-green-600'
                          : item.status === 'partial'
                          ? 'bg-yellow-100 dark:bg-yellow-900/30 text-yellow-600'
                          : 'bg-red-100 dark:bg-red-900/30 text-red-600'
                      }`}>
                        {item.status === 'completed' ? 'Completado' :
                         item.status === 'partial' ? 'Parcial' : 'Fallido'}
                      </span>
                    </div>
                    <div className="grid grid-cols-4 gap-4 text-sm">
                      <div>
                        <p className="text-gray-500 dark:text-gray-400">Operaciones</p>
                        <p className="font-medium text-gray-900 dark:text-white">
                          {item.tradesCount}
                        </p>
                      </div>
                      <div>
                        <p className="text-gray-500 dark:text-gray-400">Volumen</p>
                        <p className="font-medium text-gray-900 dark:text-white">
                          ${item.totalVolume.toLocaleString()}
                        </p>
                      </div>
                      <div>
                        <p className="text-gray-500 dark:text-gray-400">Drift Antes</p>
                        <p className="font-medium text-red-500">
                          {item.driftBefore.toFixed(1)}%
                        </p>
                      </div>
                      <div>
                        <p className="text-gray-500 dark:text-gray-400">Drift Despues</p>
                        <p className="font-medium text-green-500">
                          {item.driftAfter.toFixed(1)}%
                        </p>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="text-center py-12">
                <ClockIcon className="w-12 h-12 text-gray-400 mx-auto mb-3" />
                <p className="text-gray-500 dark:text-gray-400">
                  No hay historial de rebalanceos
                </p>
              </div>
            )}
          </>
        )}

        {/* Settings Tab */}
        {activeTab === 'settings' && (
          <div className="space-y-6">
            {/* Drift Threshold */}
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                Umbral de Drift (%)
              </label>
              <div className="flex items-center gap-4">
                <input
                  type="range"
                  min="1"
                  max="20"
                  value={settings.threshold}
                  onChange={(e) => setSettings({ ...settings, threshold: Number(e.target.value) })}
                  className="flex-1"
                />
                <span className="w-12 text-center font-medium text-gray-900 dark:text-white">
                  {settings.threshold}%
                </span>
              </div>
              <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                Se notificara cuando un activo se desvie mas de este porcentaje
              </p>
            </div>

            {/* Auto Rebalance */}
            <div>
              <div className="flex items-center justify-between">
                <div>
                  <label className="text-sm font-medium text-gray-700 dark:text-gray-300">
                    Rebalanceo Automatico
                  </label>
                  <p className="text-xs text-gray-500 dark:text-gray-400">
                    Ejecutar rebalanceo automaticamente
                  </p>
                </div>
                <button
                  onClick={() => setSettings({ ...settings, autoRebalance: !settings.autoRebalance })}
                  className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
                    settings.autoRebalance ? 'bg-purple-600' : 'bg-gray-200 dark:bg-gray-700'
                  }`}
                >
                  <span
                    className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                      settings.autoRebalance ? 'translate-x-6' : 'translate-x-1'
                    }`}
                  />
                </button>
              </div>
            </div>

            {/* Frequency */}
            {settings.autoRebalance && (
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  Frecuencia de Revision
                </label>
                <select
                  value={settings.frequency}
                  onChange={(e) => setSettings({ ...settings, frequency: e.target.value as DriftSettings['frequency'] })}
                  className="w-full px-3 py-2 bg-gray-50 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-purple-500 text-gray-900 dark:text-white"
                >
                  <option value="manual">Manual</option>
                  <option value="weekly">Semanal</option>
                  <option value="monthly">Mensual</option>
                  <option value="quarterly">Trimestral</option>
                </select>
              </div>
            )}

            {/* Notifications */}
            <div>
              <div className="flex items-center justify-between">
                <div>
                  <label className="text-sm font-medium text-gray-700 dark:text-gray-300">
                    Notificaciones de Drift
                  </label>
                  <p className="text-xs text-gray-500 dark:text-gray-400">
                    Recibir alertas cuando se supere el umbral
                  </p>
                </div>
                <button
                  onClick={() => setSettings({ ...settings, notifyOnDrift: !settings.notifyOnDrift })}
                  className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
                    settings.notifyOnDrift ? 'bg-purple-600' : 'bg-gray-200 dark:bg-gray-700'
                  }`}
                >
                  <span
                    className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                      settings.notifyOnDrift ? 'translate-x-6' : 'translate-x-1'
                    }`}
                  />
                </button>
              </div>
            </div>

            {/* Save Button */}
            <button
              className="w-full py-2 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300 font-medium rounded-lg transition-colors"
            >
              Guardar Configuracion
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

export default RebalancingPanel;
