/**
 * Portfolio Dashboard Page
 * Main dashboard for portfolio management with allocations, rebalancing, and goals
 */

import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import {
  PlusIcon,
  ArrowPathIcon,
  ChartPieIcon,
  FlagIcon,
  CurrencyDollarIcon,
  ArrowTrendingUpIcon,
  ArrowTrendingDownIcon,
  SignalIcon,
  SignalSlashIcon,
} from '@heroicons/react/24/solid';
import { usePortfolioStore } from '../../../stores/portfolioStore';
import { AllocationChart } from '../components/AllocationChart';
import { AllocationTable } from '../components/AllocationTable';
import { RebalanceCard } from '../components/RebalanceCard';
import { GoalCard } from '../components/GoalCard';
import { PerformanceChart } from '../components/PerformanceChart';

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

interface StatCardProps {
  label: string;
  value: string;
  change?: number;
  icon: React.ReactNode;
  color: string;
}

const StatCard: React.FC<StatCardProps> = ({ label, value, change, icon, color }) => {
  return (
    <div className="bg-white dark:bg-gray-800 rounded-xl p-5 shadow-lg">
      <div className="flex items-center justify-between mb-3">
        <div className={`p-2 rounded-lg ${color}`}>{icon}</div>
        {change !== undefined && (
          <div
            className={`flex items-center gap-1 text-sm font-medium ${
              change >= 0 ? 'text-green-500' : 'text-red-500'
            }`}
          >
            {change >= 0 ? (
              <ArrowTrendingUpIcon className="w-4 h-4" />
            ) : (
              <ArrowTrendingDownIcon className="w-4 h-4" />
            )}
            {Math.abs(change).toFixed(2)}%
          </div>
        )}
      </div>
      <p className="text-sm text-gray-500 dark:text-gray-400">{label}</p>
      <p className="text-xl font-bold text-gray-900 dark:text-white mt-1">{value}</p>
    </div>
  );
};

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

export default function PortfolioDashboard() {
  const [activeTab, setActiveTab] = useState<'overview' | 'goals'>('overview');

  // Store state
  const {
    portfolios,
    selectedPortfolio,
    stats,
    recommendations,
    goals,
    loading,
    isRebalancing,
    error,
    wsConnected,
    lastUpdate,
    fetchPortfolios,
    selectPortfolio,
    executeRebalance,
    deleteGoal,
    connectWebSocket,
    disconnectWebSocket,
    clearError,
  } = usePortfolioStore();

  // Initial data fetch and WebSocket connection
  useEffect(() => {
    fetchPortfolios();
    connectWebSocket();

    return () => {
      disconnectWebSocket();
    };
  }, [fetchPortfolios, connectWebSocket, disconnectWebSocket]);

  // Handle rebalance execution
  const handleRebalance = async () => {
    await executeRebalance();
  };

  // Handle goal deletion
  const handleDeleteGoal = async (goalId: string) => {
    if (confirm('¿Estás seguro de eliminar esta meta?')) {
      await deleteGoal(goalId);
    }
  };

  if (loading && portfolios.length === 0) {
    return (
      <div className="flex items-center justify-center min-h-96">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
      </div>
    );
  }

  if (error && portfolios.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center min-h-96">
        <p className="text-red-500 mb-4">{error}</p>
        <button
          onClick={() => {
            clearError();
            fetchPortfolios();
          }}
          className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
        >
          Reintentar
        </button>
      </div>
    );
  }

  return (
    <div className="max-w-7xl mx-auto px-4 py-8">
      {/* Header */}
      <div className="flex items-center justify-between mb-8">
        <div>
          <h1 className="text-3xl font-bold text-gray-900 dark:text-white">
            Portfolio Manager
          </h1>
          <div className="flex items-center gap-3 mt-1">
            <p className="text-gray-600 dark:text-gray-400">
              Gestiona tus activos y alcanza tus metas financieras
            </p>
            {/* WebSocket status indicator */}
            <div
              className={`flex items-center gap-1 text-xs px-2 py-1 rounded-full ${
                wsConnected
                  ? 'bg-green-100 dark:bg-green-900/30 text-green-600'
                  : 'bg-gray-100 dark:bg-gray-700 text-gray-500'
              }`}
              title={wsConnected ? 'Conectado en tiempo real' : 'Sin conexión en tiempo real'}
            >
              {wsConnected ? (
                <SignalIcon className="w-3 h-3" />
              ) : (
                <SignalSlashIcon className="w-3 h-3" />
              )}
              {wsConnected ? 'Live' : 'Offline'}
            </div>
          </div>
        </div>
        <div className="flex gap-3">
          <button
            onClick={fetchPortfolios}
            disabled={loading}
            className="p-2 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors disabled:opacity-50"
          >
            <ArrowPathIcon className={`w-5 h-5 text-gray-600 dark:text-gray-300 ${loading ? 'animate-spin' : ''}`} />
          </button>
          <Link
            to="/portfolio/new"
            className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors flex items-center gap-2"
          >
            <PlusIcon className="w-5 h-5" />
            Nuevo Portfolio
          </Link>
        </div>
      </div>

      {/* Last update indicator */}
      {lastUpdate && (
        <div className="text-xs text-gray-400 mb-4">
          Última actualización: {new Date(lastUpdate).toLocaleTimeString()}
        </div>
      )}

      {/* Portfolio Selector (if multiple) */}
      {portfolios.length > 1 && (
        <div className="flex gap-2 mb-6 overflow-x-auto pb-2">
          {portfolios.map((p) => (
            <div key={p.id} className="flex items-center gap-1">
              <button
                onClick={() => selectPortfolio(p)}
                className={`px-4 py-2 rounded-l-lg whitespace-nowrap transition-colors ${
                  selectedPortfolio?.id === p.id
                    ? 'bg-blue-600 text-white'
                    : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
                }`}
              >
                {p.name}
              </button>
              <Link
                to={`/portfolio/${p.id}`}
                className={`px-2 py-2 rounded-r-lg whitespace-nowrap transition-colors ${
                  selectedPortfolio?.id === p.id
                    ? 'bg-blue-700 text-white hover:bg-blue-800'
                    : 'bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-500'
                }`}
                title="Ver detalle"
              >
                <ArrowTrendingUpIcon className="w-4 h-4" />
              </Link>
            </div>
          ))}
        </div>
      )}

      {/* Tabs */}
      <div className="flex gap-4 mb-6 border-b border-gray-200 dark:border-gray-700">
        <button
          onClick={() => setActiveTab('overview')}
          className={`pb-3 px-1 font-medium transition-colors flex items-center gap-2 ${
            activeTab === 'overview'
              ? 'text-blue-600 border-b-2 border-blue-600'
              : 'text-gray-500 hover:text-gray-700 dark:hover:text-gray-300'
          }`}
        >
          <ChartPieIcon className="w-5 h-5" />
          Resumen
        </button>
        <button
          onClick={() => setActiveTab('goals')}
          className={`pb-3 px-1 font-medium transition-colors flex items-center gap-2 ${
            activeTab === 'goals'
              ? 'text-blue-600 border-b-2 border-blue-600'
              : 'text-gray-500 hover:text-gray-700 dark:hover:text-gray-300'
          }`}
        >
          <FlagIcon className="w-5 h-5" />
          Metas ({goals.length})
        </button>
      </div>

      {activeTab === 'overview' && selectedPortfolio && (
        <>
          {/* Stats Grid */}
          <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
            <StatCard
              label="Valor Total"
              value={`$${selectedPortfolio.totalValue.toLocaleString(undefined, {
                minimumFractionDigits: 2,
              })}`}
              icon={<CurrencyDollarIcon className="w-5 h-5 text-blue-600" />}
              color="bg-blue-100 dark:bg-blue-900/30"
            />
            <StatCard
              label="P&L No Realizado"
              value={`${selectedPortfolio.unrealizedPnl >= 0 ? '+' : ''}$${Math.abs(
                selectedPortfolio.unrealizedPnl
              ).toLocaleString(undefined, { minimumFractionDigits: 2 })}`}
              change={selectedPortfolio.unrealizedPnlPercent}
              icon={<ArrowTrendingUpIcon className="w-5 h-5 text-green-600" />}
              color="bg-green-100 dark:bg-green-900/30"
            />
            <StatCard
              label="Cambio Hoy"
              value={stats ? `$${stats.dayChange.toLocaleString()}` : '-'}
              change={stats?.dayChangePercent}
              icon={<ChartPieIcon className="w-5 h-5 text-purple-600" />}
              color="bg-purple-100 dark:bg-purple-900/30"
            />
            <StatCard
              label="Cambio Mensual"
              value={stats ? `$${stats.monthChange.toLocaleString()}` : '-'}
              change={stats?.monthChangePercent}
              icon={<FlagIcon className="w-5 h-5 text-orange-600" />}
              color="bg-orange-100 dark:bg-orange-900/30"
            />
          </div>

          {/* Performance Chart */}
          <div className="mb-8">
            <PerformanceChart portfolioId={selectedPortfolio.id} height={280} />
          </div>

          {/* Main Content Grid */}
          <div className="grid lg:grid-cols-3 gap-6">
            {/* Left: Allocation Chart & Table */}
            <div className="lg:col-span-2 space-y-6">
              {/* Chart Card */}
              <div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
                <h2 className="text-lg font-bold text-gray-900 dark:text-white mb-6">
                  Distribución de Activos
                </h2>
                <AllocationChart
                  allocations={selectedPortfolio.allocations}
                  size={220}
                />
              </div>

              {/* Table Card */}
              <div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
                <div className="flex items-center justify-between mb-4">
                  <h2 className="text-lg font-bold text-gray-900 dark:text-white">
                    Detalle de Posiciones
                  </h2>
                  <Link
                    to={`/portfolio/${selectedPortfolio.id}/edit`}
                    className="text-sm text-blue-600 hover:text-blue-700"
                  >
                    Editar Allocaciones
                  </Link>
                </div>
                <AllocationTable allocations={selectedPortfolio.allocations} />
              </div>
            </div>

            {/* Right: Rebalance & Performance */}
            <div className="space-y-6">
              <RebalanceCard
                recommendations={recommendations}
                onExecute={handleRebalance}
                isExecuting={isRebalancing}
              />

              {/* Best/Worst Performers */}
              {stats && (
                <div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
                  <h3 className="font-bold text-gray-900 dark:text-white mb-4">
                    Rendimiento
                  </h3>
                  <div className="space-y-4">
                    <div className="flex items-center justify-between p-3 bg-green-50 dark:bg-green-900/20 rounded-lg">
                      <div className="flex items-center gap-2">
                        <span className="text-lg">🏆</span>
                        <span className="text-gray-700 dark:text-gray-300">
                          Mejor: {stats.bestPerformer.asset}
                        </span>
                      </div>
                      <span className="text-green-600 font-medium">
                        +{stats.bestPerformer.change.toFixed(2)}%
                      </span>
                    </div>
                    <div className="flex items-center justify-between p-3 bg-red-50 dark:bg-red-900/20 rounded-lg">
                      <div className="flex items-center gap-2">
                        <span className="text-lg">📉</span>
                        <span className="text-gray-700 dark:text-gray-300">
                          Peor: {stats.worstPerformer.asset}
                        </span>
                      </div>
                      <span className="text-red-600 font-medium">
                        {stats.worstPerformer.change.toFixed(2)}%
                      </span>
                    </div>
                  </div>
                </div>
              )}

              {/* Quick Info */}
              <div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
                <h3 className="font-bold text-gray-900 dark:text-white mb-4">
                  Información
                </h3>
                <div className="space-y-3 text-sm">
                  <div className="flex justify-between">
                    <span className="text-gray-500 dark:text-gray-400">
                      Perfil de Riesgo
                    </span>
                    <span className="text-gray-900 dark:text-white capitalize">
                      {selectedPortfolio.riskProfile === 'conservative'
                        ? 'Conservador'
                        : selectedPortfolio.riskProfile === 'moderate'
                        ? 'Moderado'
                        : 'Agresivo'}
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-500 dark:text-gray-400">
                      Último Rebalanceo
                    </span>
                    <span className="text-gray-900 dark:text-white">
                      {selectedPortfolio.lastRebalanced
                        ? new Date(selectedPortfolio.lastRebalanced).toLocaleDateString()
                        : 'Nunca'}
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-500 dark:text-gray-400">
                      Activos
                    </span>
                    <span className="text-gray-900 dark:text-white">
                      {selectedPortfolio.allocations.length}
                    </span>
                  </div>
                </div>
                <Link
                  to={`/portfolio/${selectedPortfolio.id}`}
                  className="mt-4 w-full block text-center px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors"
                >
                  Ver Detalle Completo
                </Link>
              </div>
            </div>
          </div>
        </>
      )}

      {activeTab === 'goals' && (
        <>
          {/* Goals Header */}
          <div className="flex items-center justify-between mb-6">
            <p className="text-gray-600 dark:text-gray-400">
              Establece y monitorea tus metas financieras
            </p>
            <Link
              to="/portfolio/goals/new"
              className="px-4 py-2 bg-green-600 hover:bg-green-700 text-white font-medium rounded-lg transition-colors flex items-center gap-2"
            >
              <PlusIcon className="w-5 h-5" />
              Nueva Meta
            </Link>
          </div>

          {goals.length === 0 ? (
            <div className="text-center py-16 bg-white dark:bg-gray-800 rounded-xl shadow-lg">
              <span className="text-6xl mb-4 block">🎯</span>
              <h3 className="text-xl font-bold text-gray-900 dark:text-white mb-2">
                No tienes metas definidas
              </h3>
              <p className="text-gray-600 dark:text-gray-400 mb-6">
                Establece tus objetivos financieros y monitorea tu progreso
              </p>
              <Link
                to="/portfolio/goals/new"
                className="inline-block px-6 py-3 bg-green-600 hover:bg-green-700 text-white font-medium rounded-lg transition-colors"
              >
                Crear Primera Meta
              </Link>
            </div>
          ) : (
            <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
              {goals.map((goal) => (
                <GoalCard
                  key={goal.id}
                  goal={goal}
                  onDelete={handleDeleteGoal}
                />
              ))}
            </div>
          )}
        </>
      )}

      {/* Empty State for no portfolios */}
      {portfolios.length === 0 && (
        <div className="text-center py-16 bg-white dark:bg-gray-800 rounded-xl shadow-lg">
          <span className="text-6xl mb-4 block">📊</span>
          <h3 className="text-xl font-bold text-gray-900 dark:text-white mb-2">
            Crea tu primer Portfolio
          </h3>
          <p className="text-gray-600 dark:text-gray-400 mb-6">
            Diversifica tus inversiones según tu perfil de riesgo
          </p>
          <Link
            to="/portfolio/new"
            className="inline-block px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors"
          >
            Crear Portfolio
          </Link>
        </div>
      )}
    </div>
  );
}
