/**
 * LeaderboardTable Component
 * Displays gamification leaderboard with rankings
 */

import React from 'react';
import { Trophy, Medal, Flame, Zap, TrendingUp, TrendingDown, Minus } from 'lucide-react';
import type { LeaderboardEntry, UserLeaderboardPosition } from '../../types/education.types';

interface LeaderboardTableProps {
  entries: LeaderboardEntry[];
  currentUserId?: string;
  userPosition?: UserLeaderboardPosition;
  period?: 'all_time' | 'month' | 'week';
  onPeriodChange?: (period: 'all_time' | 'month' | 'week') => void;
  showRankChange?: boolean;
}

const periodLabels = {
  all_time: 'Todo el tiempo',
  month: 'Este mes',
  week: 'Esta semana',
};

const getRankIcon = (rank: number) => {
  switch (rank) {
    case 1:
      return <Trophy className="w-5 h-5 text-yellow-400" />;
    case 2:
      return <Medal className="w-5 h-5 text-gray-300" />;
    case 3:
      return <Medal className="w-5 h-5 text-amber-600" />;
    default:
      return null;
  }
};

const getRankStyle = (rank: number) => {
  switch (rank) {
    case 1:
      return 'bg-gradient-to-r from-yellow-500/20 to-orange-500/20 border-yellow-500/30';
    case 2:
      return 'bg-gradient-to-r from-gray-400/20 to-gray-500/20 border-gray-400/30';
    case 3:
      return 'bg-gradient-to-r from-amber-600/20 to-orange-600/20 border-amber-500/30';
    default:
      return 'bg-gray-800 border-gray-700';
  }
};

export const LeaderboardTable: React.FC<LeaderboardTableProps> = ({
  entries,
  currentUserId,
  userPosition,
  period = 'all_time',
  onPeriodChange,
  showRankChange = false,
}) => {
  return (
    <div className="bg-gray-800 rounded-xl border border-gray-700 overflow-hidden">
      {/* Header */}
      <div className="p-4 border-b border-gray-700">
        <div className="flex items-center justify-between">
          <h3 className="font-semibold text-white flex items-center gap-2">
            <Trophy className="w-5 h-5 text-yellow-400" />
            Tabla de Clasificación
          </h3>

          {/* Period Selector */}
          {onPeriodChange && (
            <div className="flex bg-gray-900 rounded-lg p-1">
              {(['week', 'month', 'all_time'] as const).map((p) => (
                <button
                  key={p}
                  onClick={() => onPeriodChange(p)}
                  className={`px-3 py-1 text-xs rounded-md transition-colors ${
                    period === p
                      ? 'bg-blue-500 text-white'
                      : 'text-gray-400 hover:text-white'
                  }`}
                >
                  {periodLabels[p]}
                </button>
              ))}
            </div>
          )}
        </div>

        {/* User Position Summary */}
        {userPosition && userPosition.rank && (
          <div className="mt-3 p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg flex items-center justify-between">
            <div className="flex items-center gap-2">
              <span className="text-sm text-gray-400">Tu posición:</span>
              <span className="text-lg font-bold text-blue-400">#{userPosition.rank}</span>
            </div>
            <div className="text-sm text-gray-400">
              Top {userPosition.percentile.toFixed(0)}% de {userPosition.totalUsers.toLocaleString()} usuarios
            </div>
          </div>
        )}
      </div>

      {/* Table Header */}
      <div className="grid grid-cols-12 gap-2 px-4 py-2 bg-gray-900/50 text-xs text-gray-500 uppercase">
        <div className="col-span-1 text-center">#</div>
        <div className="col-span-5">Usuario</div>
        <div className="col-span-2 text-center">Nivel</div>
        <div className="col-span-2 text-right">XP</div>
        <div className="col-span-2 text-center">Racha</div>
      </div>

      {/* Entries */}
      <div className="divide-y divide-gray-700/50">
        {entries.map((entry, index) => {
          const isCurrentUser = entry.userId === currentUserId;
          const rankIcon = getRankIcon(entry.rank);
          const rankStyle = getRankStyle(entry.rank);

          return (
            <div
              key={entry.userId}
              className={`grid grid-cols-12 gap-2 px-4 py-3 items-center transition-colors ${
                isCurrentUser
                  ? 'bg-blue-500/10 border-l-2 border-l-blue-500'
                  : index < 3
                  ? rankStyle
                  : 'hover:bg-gray-700/30'
              }`}
            >
              {/* Rank */}
              <div className="col-span-1 flex items-center justify-center">
                {rankIcon || (
                  <span className={`font-medium ${isCurrentUser ? 'text-blue-400' : 'text-gray-400'}`}>
                    {entry.rank}
                  </span>
                )}
              </div>

              {/* User */}
              <div className="col-span-5 flex items-center gap-3">
                {entry.avatarUrl ? (
                  <img
                    src={entry.avatarUrl}
                    alt={entry.userName}
                    className="w-8 h-8 rounded-full"
                  />
                ) : (
                  <div className="w-8 h-8 rounded-full bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center">
                    <span className="text-sm font-medium text-white">
                      {entry.userName.charAt(0).toUpperCase()}
                    </span>
                  </div>
                )}
                <div className="min-w-0">
                  <p className={`font-medium truncate ${isCurrentUser ? 'text-blue-400' : 'text-white'}`}>
                    {entry.userName}
                    {isCurrentUser && <span className="text-xs text-gray-400 ml-1">(tú)</span>}
                  </p>
                  <p className="text-xs text-gray-500">
                    {entry.coursesCompleted} cursos completados
                  </p>
                </div>
              </div>

              {/* Level */}
              <div className="col-span-2 flex justify-center">
                <div className="px-2 py-1 bg-purple-500/20 text-purple-400 rounded-full text-sm font-medium">
                  Nv. {entry.currentLevel}
                </div>
              </div>

              {/* XP */}
              <div className="col-span-2 text-right">
                <span className="font-medium text-white flex items-center justify-end gap-1">
                  <Zap className="w-4 h-4 text-yellow-400" />
                  {entry.totalXp.toLocaleString()}
                </span>
              </div>

              {/* Streak */}
              <div className="col-span-2 flex items-center justify-center gap-1">
                <Flame
                  className={`w-4 h-4 ${
                    entry.currentStreak > 0 ? 'text-orange-400' : 'text-gray-500'
                  }`}
                />
                <span className={entry.currentStreak > 0 ? 'text-orange-400' : 'text-gray-500'}>
                  {entry.currentStreak}
                </span>
              </div>

              {/* Rank Change (optional) */}
              {showRankChange && (
                <div className="col-span-1 flex justify-center">
                  <TrendingUp className="w-4 h-4 text-green-400" />
                </div>
              )}
            </div>
          );
        })}
      </div>

      {/* Empty State */}
      {entries.length === 0 && (
        <div className="p-8 text-center text-gray-400">
          No hay datos disponibles para este período.
        </div>
      )}
    </div>
  );
};

export default LeaderboardTable;
