/**
 * Leaderboard Page
 * Shows gamification rankings with period selection
 */

import React, { useEffect, useState } from 'react';
import { Trophy, Medal, Zap, Flame, Users, TrendingUp, Loader2 } from 'lucide-react';
import { useEducationStore } from '../../../stores/educationStore';
import { LeaderboardTable, XPProgress, StreakCounter } from '../../../components/education';

type Period = 'all_time' | 'month' | 'week';

export default function Leaderboard() {
  const {
    leaderboard,
    myLeaderboardPosition,
    gamificationProfile,
    streakStats,
    loadingGamification,
    fetchLeaderboard,
    fetchMyLeaderboardPosition,
    fetchGamificationProfile,
    fetchStreakStats,
  } = useEducationStore();

  const [period, setPeriod] = useState<Period>('all_time');

  useEffect(() => {
    fetchGamificationProfile();
    fetchStreakStats();
  }, [fetchGamificationProfile, fetchStreakStats]);

  useEffect(() => {
    fetchLeaderboard(period, 100);
    fetchMyLeaderboardPosition(period);
  }, [period, fetchLeaderboard, fetchMyLeaderboardPosition]);

  const handlePeriodChange = (newPeriod: Period) => {
    setPeriod(newPeriod);
  };

  // Get top 3 for podium
  const top3 = leaderboard.slice(0, 3);
  const restOfLeaderboard = leaderboard.slice(3);

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white flex items-center gap-3">
            <Trophy className="w-8 h-8 text-yellow-400" />
            Tabla de Clasificación
          </h1>
          <p className="text-gray-400">
            Compite con otros estudiantes y sube en el ranking
          </p>
        </div>
      </div>

      {/* User Stats Summary */}
      {gamificationProfile && (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          <XPProgress
            levelProgress={gamificationProfile.levelProgress}
            showDetails={false}
            size="md"
          />

          {streakStats && <StreakCounter streakStats={streakStats} />}

          {/* Position Card */}
          <div className="bg-gray-800 rounded-xl border border-gray-700 p-4">
            <h3 className="font-medium text-white mb-4 flex items-center gap-2">
              <TrendingUp className="w-5 h-5 text-blue-400" />
              Tu Posición
            </h3>
            {myLeaderboardPosition?.rank ? (
              <div className="text-center">
                <div className="text-4xl font-bold text-blue-400 mb-2">
                  #{myLeaderboardPosition.rank}
                </div>
                <p className="text-sm text-gray-400">
                  Top {myLeaderboardPosition.percentile.toFixed(0)}% de{' '}
                  {myLeaderboardPosition.totalUsers.toLocaleString()} usuarios
                </p>
              </div>
            ) : (
              <div className="text-center text-gray-400">
                <p>Completa cursos para aparecer en el ranking</p>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Podium (Top 3) */}
      {top3.length >= 3 && (
        <div className="bg-gradient-to-b from-gray-800 to-gray-900 rounded-xl border border-gray-700 p-6">
          <h2 className="text-lg font-semibold text-white text-center mb-8">
            Top 3 del Podio
          </h2>
          <div className="flex items-end justify-center gap-4">
            {/* 2nd Place */}
            <div className="flex flex-col items-center">
              <div className="w-20 h-20 rounded-full bg-gradient-to-br from-gray-300 to-gray-400 flex items-center justify-center mb-3 border-4 border-gray-500 shadow-lg">
                {top3[1]?.avatarUrl ? (
                  <img
                    src={top3[1].avatarUrl}
                    alt={top3[1].userName}
                    className="w-full h-full rounded-full object-cover"
                  />
                ) : (
                  <span className="text-2xl font-bold text-gray-700">
                    {top3[1]?.userName.charAt(0).toUpperCase()}
                  </span>
                )}
              </div>
              <Medal className="w-8 h-8 text-gray-300 mb-2" />
              <p className="font-medium text-white text-sm truncate max-w-24">
                {top3[1]?.userName}
              </p>
              <p className="text-xs text-gray-400 flex items-center gap-1">
                <Zap className="w-3 h-3 text-yellow-400" />
                {top3[1]?.totalXp.toLocaleString()}
              </p>
              <div className="w-24 h-20 bg-gray-600 rounded-t-lg mt-3" />
            </div>

            {/* 1st Place */}
            <div className="flex flex-col items-center -mt-8">
              <div className="w-24 h-24 rounded-full bg-gradient-to-br from-yellow-400 to-orange-500 flex items-center justify-center mb-3 border-4 border-yellow-300 shadow-xl animate-pulse">
                {top3[0]?.avatarUrl ? (
                  <img
                    src={top3[0].avatarUrl}
                    alt={top3[0].userName}
                    className="w-full h-full rounded-full object-cover"
                  />
                ) : (
                  <span className="text-3xl font-bold text-yellow-900">
                    {top3[0]?.userName.charAt(0).toUpperCase()}
                  </span>
                )}
              </div>
              <Trophy className="w-10 h-10 text-yellow-400 mb-2" />
              <p className="font-bold text-white truncate max-w-28">
                {top3[0]?.userName}
              </p>
              <p className="text-sm text-yellow-400 flex items-center gap-1">
                <Zap className="w-4 h-4" />
                {top3[0]?.totalXp.toLocaleString()}
              </p>
              <div className="w-28 h-28 bg-yellow-600/50 rounded-t-lg mt-3" />
            </div>

            {/* 3rd Place */}
            <div className="flex flex-col items-center">
              <div className="w-20 h-20 rounded-full bg-gradient-to-br from-amber-600 to-orange-700 flex items-center justify-center mb-3 border-4 border-amber-500 shadow-lg">
                {top3[2]?.avatarUrl ? (
                  <img
                    src={top3[2].avatarUrl}
                    alt={top3[2].userName}
                    className="w-full h-full rounded-full object-cover"
                  />
                ) : (
                  <span className="text-2xl font-bold text-amber-900">
                    {top3[2]?.userName.charAt(0).toUpperCase()}
                  </span>
                )}
              </div>
              <Medal className="w-8 h-8 text-amber-600 mb-2" />
              <p className="font-medium text-white text-sm truncate max-w-24">
                {top3[2]?.userName}
              </p>
              <p className="text-xs text-gray-400 flex items-center gap-1">
                <Zap className="w-3 h-3 text-yellow-400" />
                {top3[2]?.totalXp.toLocaleString()}
              </p>
              <div className="w-24 h-16 bg-amber-700/50 rounded-t-lg mt-3" />
            </div>
          </div>
        </div>
      )}

      {/* Full Leaderboard Table */}
      {loadingGamification ? (
        <div className="flex items-center justify-center py-12">
          <Loader2 className="w-8 h-8 text-blue-500 animate-spin" />
        </div>
      ) : (
        <LeaderboardTable
          entries={restOfLeaderboard.length > 0 ? restOfLeaderboard : leaderboard}
          currentUserId={gamificationProfile?.userId}
          userPosition={myLeaderboardPosition || undefined}
          period={period}
          onPeriodChange={handlePeriodChange}
        />
      )}

      {/* Empty State */}
      {!loadingGamification && leaderboard.length === 0 && (
        <div className="text-center py-12 bg-gray-800 rounded-xl border border-gray-700">
          <Users className="w-16 h-16 text-gray-500 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-white mb-2">
            No hay datos en el leaderboard
          </h3>
          <p className="text-gray-400">
            Sé el primero en completar cursos y aparecer aquí
          </p>
        </div>
      )}

      {/* Info Section */}
      <div className="bg-gray-800 rounded-xl border border-gray-700 p-6">
        <h3 className="font-semibold text-white mb-4">¿Cómo funciona el ranking?</h3>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          <div className="flex items-start gap-3">
            <div className="p-2 bg-purple-500/20 rounded-lg">
              <Zap className="w-5 h-5 text-purple-400" />
            </div>
            <div>
              <h4 className="font-medium text-white">Gana XP</h4>
              <p className="text-sm text-gray-400">
                Completa lecciones, quizzes y cursos para ganar puntos de experiencia
              </p>
            </div>
          </div>
          <div className="flex items-start gap-3">
            <div className="p-2 bg-orange-500/20 rounded-lg">
              <Flame className="w-5 h-5 text-orange-400" />
            </div>
            <div>
              <h4 className="font-medium text-white">Mantén tu racha</h4>
              <p className="text-sm text-gray-400">
                Estudia cada día para obtener bonificaciones de XP
              </p>
            </div>
          </div>
          <div className="flex items-start gap-3">
            <div className="p-2 bg-yellow-500/20 rounded-lg">
              <Trophy className="w-5 h-5 text-yellow-400" />
            </div>
            <div>
              <h4 className="font-medium text-white">Sube de nivel</h4>
              <p className="text-sm text-gray-400">
                Acumula XP para subir de nivel y desbloquear logros
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
