'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import {
  Users,
  Trophy,
  Search,
  Crown,
  Star,
  TrendingUp,
  Shield,
  Target,
  Award,
  ArrowLeft,
  Medal,
  Percent,
  Hash,
  Globe,
  Languages,
} from 'lucide-react';
import Button from '@/components/ui/Button';
import Input from '@/components/ui/Input';
import Heading from '@/components/ui/Heading';
import { getGetAllTeamsQuery, getGetTeamMembersQuery, getDriverStats } from '@/lib/di-container';
import type { Team } from '@gridpilot/racing';

// ============================================================================
// TYPES
// ============================================================================

type SkillLevel = 'beginner' | 'intermediate' | 'advanced' | 'pro';
type SortBy = 'rating' | 'wins' | 'winRate' | 'races';

interface TeamDisplayData {
  id: string;
  name: string;
  memberCount: number;
  rating: number | null;
  totalWins: number;
  totalRaces: number;
  performanceLevel: SkillLevel;
  isRecruiting: boolean;
  createdAt: Date;
  description?: string;
  specialization?: 'endurance' | 'sprint' | 'mixed';
  region?: string;
  languages?: string[];
}

// ============================================================================
// SKILL LEVEL CONFIG
// ============================================================================

const SKILL_LEVELS: {
  id: SkillLevel;
  label: string;
  icon: React.ElementType;
  color: string;
  bgColor: string;
  borderColor: string;
}[] = [
  {
    id: 'pro',
    label: 'Pro',
    icon: Crown,
    color: 'text-yellow-400',
    bgColor: 'bg-yellow-400/10',
    borderColor: 'border-yellow-400/30',
  },
  {
    id: 'advanced',
    label: 'Advanced',
    icon: Star,
    color: 'text-purple-400',
    bgColor: 'bg-purple-400/10',
    borderColor: 'border-purple-400/30',
  },
  {
    id: 'intermediate',
    label: 'Intermediate',
    icon: TrendingUp,
    color: 'text-primary-blue',
    bgColor: 'bg-primary-blue/10',
    borderColor: 'border-primary-blue/30',
  },
  {
    id: 'beginner',
    label: 'Beginner',
    icon: Shield,
    color: 'text-green-400',
    bgColor: 'bg-green-400/10',
    borderColor: 'border-green-400/30',
  },
];

// ============================================================================
// SORT OPTIONS
// ============================================================================

const SORT_OPTIONS: { id: SortBy; label: string; icon: React.ElementType }[] = [
  { id: 'rating', label: 'Rating', icon: Star },
  { id: 'wins', label: 'Total Wins', icon: Trophy },
  { id: 'winRate', label: 'Win Rate', icon: Percent },
  { id: 'races', label: 'Races', icon: Hash },
];

// ============================================================================
// TOP THREE PODIUM COMPONENT
// ============================================================================

interface TopThreePodiumProps {
  teams: TeamDisplayData[];
  onTeamClick: (teamId: string) => void;
}

function TopThreePodium({ teams, onTeamClick }: TopThreePodiumProps) {
  const top3 = teams.slice(0, 3);
  if (top3.length < 3) return null;

  // Display order: 2nd, 1st, 3rd
  const podiumOrder = [top3[1], top3[0], top3[2]];
  const podiumHeights = ['h-28', 'h-36', 'h-20'];
  const podiumPositions = [2, 1, 3];

  const getPositionColor = (position: number) => {
    switch (position) {
      case 1:
        return 'text-yellow-400';
      case 2:
        return 'text-gray-300';
      case 3:
        return 'text-amber-600';
      default:
        return 'text-gray-500';
    }
  };

  const getGradient = (position: number) => {
    switch (position) {
      case 1:
        return 'from-yellow-400/30 via-yellow-500/20 to-yellow-600/10';
      case 2:
        return 'from-gray-300/30 via-gray-400/20 to-gray-500/10';
      case 3:
        return 'from-amber-500/30 via-amber-600/20 to-amber-700/10';
      default:
        return 'from-gray-600/30 to-gray-700/10';
    }
  };

  const getBorderColor = (position: number) => {
    switch (position) {
      case 1:
        return 'border-yellow-400/50';
      case 2:
        return 'border-gray-300/50';
      case 3:
        return 'border-amber-600/50';
      default:
        return 'border-charcoal-outline';
    }
  };

  return (
    <div className="mb-10 p-8 rounded-2xl bg-gradient-to-br from-iron-gray/60 to-iron-gray/30 border border-charcoal-outline">
      <div className="flex items-center justify-center gap-2 mb-8">
        <Trophy className="w-6 h-6 text-yellow-400" />
        <h2 className="text-xl font-bold text-white">Top 3 Teams</h2>
      </div>

      <div className="flex items-end justify-center gap-4 md:gap-8">
        {podiumOrder.map((team, index) => {
          const position = podiumPositions[index];
          const levelConfig = SKILL_LEVELS.find((l) => l.id === team.performanceLevel);
          const LevelIcon = levelConfig?.icon || Shield;

          return (
            <button
              key={team.id}
              type="button"
              onClick={() => onTeamClick(team.id)}
              className="flex flex-col items-center group"
            >
              {/* Team card */}
              <div
                className={`relative mb-4 p-4 rounded-xl bg-gradient-to-br ${getGradient(position)} border ${getBorderColor(position)} transition-all group-hover:scale-105 group-hover:shadow-lg`}
              >
                {/* Crown for 1st place */}
                {position === 1 && (
                  <div className="absolute -top-4 left-1/2 -translate-x-1/2">
                    <div className="relative">
                      <Crown className="w-8 h-8 text-yellow-400 animate-pulse" />
                      <div className="absolute inset-0 w-8 h-8 bg-yellow-400/30 blur-md rounded-full" />
                    </div>
                  </div>
                )}

                {/* Team icon */}
                <div
                  className={`flex h-16 w-16 md:h-20 md:w-20 items-center justify-center rounded-xl ${levelConfig?.bgColor} border ${levelConfig?.borderColor} mb-3`}
                >
                  <LevelIcon className={`w-8 h-8 md:w-10 md:h-10 ${levelConfig?.color}`} />
                </div>

                {/* Team name */}
                <p className="text-white font-bold text-sm md:text-base text-center max-w-[120px] truncate group-hover:text-purple-400 transition-colors">
                  {team.name}
                </p>

                {/* Rating */}
                <p className={`text-lg md:text-xl font-mono font-bold ${getPositionColor(position)} text-center`}>
                  {team.rating?.toLocaleString() ?? '—'}
                </p>

                {/* Stats row */}
                <div className="flex items-center justify-center gap-3 mt-2 text-xs text-gray-400">
                  <span className="flex items-center gap-1">
                    <Trophy className="w-3 h-3 text-performance-green" />
                    {team.totalWins}
                  </span>
                  <span className="flex items-center gap-1">
                    <Users className="w-3 h-3 text-purple-400" />
                    {team.memberCount}
                  </span>
                </div>
              </div>

              {/* Podium stand */}
              <div
                className={`${podiumHeights[index]} w-20 md:w-28 rounded-t-lg bg-gradient-to-t ${getGradient(position)} border-t border-x ${getBorderColor(position)} flex items-start justify-center pt-3`}
              >
                <span className={`text-2xl md:text-3xl font-bold ${getPositionColor(position)}`}>
                  {position}
                </span>
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ============================================================================
// MAIN PAGE COMPONENT
// ============================================================================

export default function TeamLeaderboardPage() {
  const router = useRouter();
  const [realTeams, setRealTeams] = useState<TeamDisplayData[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [sortBy, setSortBy] = useState<SortBy>('rating');
  const [filterLevel, setFilterLevel] = useState<SkillLevel | 'all'>('all');

  useEffect(() => {
    loadTeams();
  }, []);

  const loadTeams = async () => {
    try {
      const allTeamsQuery = getGetAllTeamsQuery();
      const teamMembersQuery = getGetTeamMembersQuery();

      const allTeams = await allTeamsQuery.execute();
      const teamData: TeamDisplayData[] = [];

      await Promise.all(
        allTeams.map(async (team: Team) => {
          const memberships = await teamMembersQuery.execute({ teamId: team.id });
          const memberCount = memberships.length;

          let ratingSum = 0;
          let ratingCount = 0;
          let totalWins = 0;
          let totalRaces = 0;

          for (const membership of memberships) {
            const stats = getDriverStats(membership.driverId);
            if (!stats) continue;

            if (typeof stats.rating === 'number') {
              ratingSum += stats.rating;
              ratingCount += 1;
            }

            totalWins += stats.wins ?? 0;
            totalRaces += stats.totalRaces ?? 0;
          }

          const averageRating = ratingCount > 0 ? ratingSum / ratingCount : null;

          let performanceLevel: TeamDisplayData['performanceLevel'] = 'beginner';
          if (averageRating !== null) {
            if (averageRating >= 4500) performanceLevel = 'pro';
            else if (averageRating >= 3000) performanceLevel = 'advanced';
            else if (averageRating >= 2000) performanceLevel = 'intermediate';
          }

          teamData.push({
            id: team.id,
            name: team.name,
            memberCount,
            rating: averageRating,
            totalWins,
            totalRaces,
            performanceLevel,
            isRecruiting: true,
            createdAt: new Date(),
          });
        }),
      );

      setRealTeams(teamData);
    } catch (error) {
      console.error('Failed to load teams:', error);
    } finally {
      setLoading(false);
    }
  };

  const teams = realTeams;

  const handleTeamClick = (teamId: string) => {
    if (teamId.startsWith('demo-team-')) {
      return;
    }
    router.push(`/teams/${teamId}`);
  };

  // Filter and sort teams
  const filteredAndSortedTeams = teams
    .filter((team) => {
      // Search filter
      if (searchQuery) {
        const query = searchQuery.toLowerCase();
        if (!team.name.toLowerCase().includes(query) && !(team.description ?? '').toLowerCase().includes(query)) {
          return false;
        }
      }
      // Level filter
      if (filterLevel !== 'all' && team.performanceLevel !== filterLevel) {
        return false;
      }
      // Must have rating for leaderboard
      return team.rating !== null;
    })
    .sort((a, b) => {
      switch (sortBy) {
        case 'rating':
          return (b.rating ?? 0) - (a.rating ?? 0);
        case 'wins':
          return b.totalWins - a.totalWins;
        case 'winRate': {
          const aRate = a.totalRaces > 0 ? a.totalWins / a.totalRaces : 0;
          const bRate = b.totalRaces > 0 ? b.totalWins / b.totalRaces : 0;
          return bRate - aRate;
        }
        case 'races':
          return b.totalRaces - a.totalRaces;
        default:
          return 0;
      }
    });

  const getMedalColor = (position: number) => {
    switch (position) {
      case 0:
        return 'text-yellow-400';
      case 1:
        return 'text-gray-300';
      case 2:
        return 'text-amber-600';
      default:
        return 'text-gray-500';
    }
  };

  const getMedalBg = (position: number) => {
    switch (position) {
      case 0:
        return 'bg-gradient-to-br from-yellow-400/20 to-yellow-600/10 border-yellow-400/40';
      case 1:
        return 'bg-gradient-to-br from-gray-300/20 to-gray-400/10 border-gray-300/40';
      case 2:
        return 'bg-gradient-to-br from-amber-600/20 to-amber-700/10 border-amber-600/40';
      default:
        return 'bg-iron-gray/50 border-charcoal-outline';
    }
  };

  if (loading) {
    return (
      <div className="max-w-7xl mx-auto px-4">
        <div className="flex items-center justify-center min-h-[400px]">
          <div className="flex flex-col items-center gap-4">
            <div className="w-10 h-10 border-2 border-yellow-400 border-t-transparent rounded-full animate-spin" />
            <p className="text-gray-400">Loading leaderboard...</p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-7xl mx-auto px-4 pb-12">
      {/* Header */}
      <div className="mb-8">
        <Button
          variant="secondary"
          onClick={() => router.push('/teams')}
          className="flex items-center gap-2 mb-6"
        >
          <ArrowLeft className="w-4 h-4" />
          Back to Teams
        </Button>

        <div className="flex items-center gap-4 mb-2">
          <div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-gradient-to-br from-yellow-400/20 to-amber-600/10 border border-yellow-400/30">
            <Award className="w-7 h-7 text-yellow-400" />
          </div>
          <div>
            <Heading level={1} className="text-3xl lg:text-4xl">
              Team Leaderboard
            </Heading>
            <p className="text-gray-400">Rankings of all teams by performance metrics</p>
          </div>
        </div>
      </div>

      {/* Filters and Search */}
      <div className="mb-6 space-y-4">
        {/* Search and Level Filter Row */}
        <div className="flex flex-col lg:flex-row gap-4">
          <div className="flex-1 relative max-w-md">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-500" />
            <Input
              type="text"
              placeholder="Search teams..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-11"
            />
          </div>

          {/* Level Filter */}
          <div className="flex items-center gap-2">
            <button
              type="button"
              onClick={() => setFilterLevel('all')}
              className={`px-3 py-2 rounded-lg text-sm font-medium transition-all ${
                filterLevel === 'all'
                  ? 'bg-purple-600 text-white'
                  : 'bg-iron-gray/50 text-gray-400 border border-charcoal-outline hover:text-white'
              }`}
            >
              All Levels
            </button>
            {SKILL_LEVELS.map((level) => {
              const LevelIcon = level.icon;
              return (
                <button
                  key={level.id}
                  type="button"
                  onClick={() => setFilterLevel(level.id)}
                  className={`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-all ${
                    filterLevel === level.id
                      ? `${level.bgColor} ${level.color} border ${level.borderColor}`
                      : 'bg-iron-gray/50 text-gray-400 border border-charcoal-outline hover:text-white'
                  }`}
                >
                  <LevelIcon className="w-4 h-4" />
                  {level.label}
                </button>
              );
            })}
          </div>
        </div>

        {/* Sort Options */}
        <div className="flex items-center gap-2">
          <span className="text-sm text-gray-500">Sort by:</span>
          <div className="flex items-center gap-1 p-1 rounded-lg bg-iron-gray/50 border border-charcoal-outline">
            {SORT_OPTIONS.map((option) => (
              <button
                key={option.id}
                type="button"
                onClick={() => setSortBy(option.id)}
                className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-all ${
                  sortBy === option.id
                    ? 'bg-purple-600 text-white'
                    : 'text-gray-400 hover:text-white hover:bg-iron-gray'
                }`}
              >
                <option.icon className="w-3.5 h-3.5" />
                {option.label}
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* Podium for Top 3 - only show when viewing by rating without filters */}
      {sortBy === 'rating' && filterLevel === 'all' && !searchQuery && filteredAndSortedTeams.length >= 3 && (
        <TopThreePodium teams={filteredAndSortedTeams} onTeamClick={handleTeamClick} />
      )}

      {/* Stats Summary */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
        <div className="p-4 rounded-xl bg-iron-gray/30 border border-charcoal-outline">
          <div className="flex items-center gap-2 mb-1">
            <Users className="w-4 h-4 text-purple-400" />
            <span className="text-xs text-gray-500">Total Teams</span>
          </div>
          <p className="text-2xl font-bold text-white">{filteredAndSortedTeams.length}</p>
        </div>
        <div className="p-4 rounded-xl bg-iron-gray/30 border border-charcoal-outline">
          <div className="flex items-center gap-2 mb-1">
            <Crown className="w-4 h-4 text-yellow-400" />
            <span className="text-xs text-gray-500">Pro Teams</span>
          </div>
          <p className="text-2xl font-bold text-white">
            {filteredAndSortedTeams.filter((t) => t.performanceLevel === 'pro').length}
          </p>
        </div>
        <div className="p-4 rounded-xl bg-iron-gray/30 border border-charcoal-outline">
          <div className="flex items-center gap-2 mb-1">
            <Trophy className="w-4 h-4 text-performance-green" />
            <span className="text-xs text-gray-500">Total Wins</span>
          </div>
          <p className="text-2xl font-bold text-white">
            {filteredAndSortedTeams.reduce((sum, t) => sum + t.totalWins, 0)}
          </p>
        </div>
        <div className="p-4 rounded-xl bg-iron-gray/30 border border-charcoal-outline">
          <div className="flex items-center gap-2 mb-1">
            <Target className="w-4 h-4 text-neon-aqua" />
            <span className="text-xs text-gray-500">Total Races</span>
          </div>
          <p className="text-2xl font-bold text-white">
            {filteredAndSortedTeams.reduce((sum, t) => sum + t.totalRaces, 0)}
          </p>
        </div>
      </div>

      {/* Leaderboard Table */}
      <div className="rounded-xl bg-iron-gray/30 border border-charcoal-outline overflow-hidden">
        {/* Table Header */}
        <div className="grid grid-cols-12 gap-4 px-4 py-3 bg-iron-gray/50 border-b border-charcoal-outline text-xs font-medium text-gray-500 uppercase tracking-wider">
          <div className="col-span-1 text-center">Rank</div>
          <div className="col-span-4 lg:col-span-5">Team</div>
          <div className="col-span-2 text-center hidden lg:block">Members</div>
          <div className="col-span-2 lg:col-span-1 text-center">Rating</div>
          <div className="col-span-2 lg:col-span-1 text-center">Wins</div>
          <div className="col-span-2 text-center">Win Rate</div>
        </div>

        {/* Table Body */}
        <div className="divide-y divide-charcoal-outline/50">
          {filteredAndSortedTeams.map((team, index) => {
            const levelConfig = SKILL_LEVELS.find((l) => l.id === team.performanceLevel);
            const LevelIcon = levelConfig?.icon || Shield;
            const winRate = team.totalRaces > 0 ? ((team.totalWins / team.totalRaces) * 100).toFixed(1) : '0.0';

            return (
              <button
                key={team.id}
                type="button"
                onClick={() => handleTeamClick(team.id)}
                className="grid grid-cols-12 gap-4 px-4 py-4 w-full text-left hover:bg-iron-gray/30 transition-colors group"
              >
                {/* Position */}
                <div className="col-span-1 flex items-center justify-center">
                  <div
                    className={`flex h-9 w-9 items-center justify-center rounded-full text-sm font-bold border ${getMedalBg(index)} ${getMedalColor(index)}`}
                  >
                    {index < 3 ? (
                      <Medal className="w-4 h-4" />
                    ) : (
                      index + 1
                    )}
                  </div>
                </div>

                {/* Team Info */}
                <div className="col-span-4 lg:col-span-5 flex items-center gap-3">
                  <div className={`flex h-10 w-10 items-center justify-center rounded-lg ${levelConfig?.bgColor} border ${levelConfig?.borderColor}`}>
                    <LevelIcon className={`w-5 h-5 ${levelConfig?.color}`} />
                  </div>
                  <div className="min-w-0 flex-1">
                    <p className="text-white font-semibold truncate group-hover:text-purple-400 transition-colors">
                      {team.name}
                    </p>
                    <div className="flex items-center gap-2 text-xs text-gray-500 flex-wrap">
                      <span className={`${levelConfig?.color}`}>{levelConfig?.label}</span>
                      {team.region && (
                        <span className="flex items-center gap-1 text-gray-400">
                          <Globe className="w-3 h-3 text-neon-aqua" />
                          {team.region}
                        </span>
                      )}
                      {team.languages && team.languages.length > 0 && (
                        <span className="flex items-center gap-1 text-gray-400">
                          <Languages className="w-3 h-3 text-purple-400" />
                          {team.languages.slice(0, 2).join(', ')}
                          {team.languages.length > 2 && ` +${team.languages.length - 2}`}
                        </span>
                      )}
                      {team.isRecruiting && (
                        <span className="flex items-center gap-1 text-performance-green">
                          <div className="w-1.5 h-1.5 rounded-full bg-performance-green animate-pulse" />
                          Recruiting
                        </span>
                      )}
                    </div>
                  </div>
                </div>

                {/* Members */}
                <div className="col-span-2 items-center justify-center hidden lg:flex">
                  <span className="flex items-center gap-1 text-gray-400">
                    <Users className="w-4 h-4" />
                    {team.memberCount}
                  </span>
                </div>

                {/* Rating */}
                <div className="col-span-2 lg:col-span-1 flex items-center justify-center">
                  <span className={`font-mono font-semibold ${sortBy === 'rating' ? 'text-purple-400' : 'text-white'}`}>
                    {team.rating?.toLocaleString() ?? '—'}
                  </span>
                </div>

                {/* Wins */}
                <div className="col-span-2 lg:col-span-1 flex items-center justify-center">
                  <span className={`font-mono font-semibold ${sortBy === 'wins' ? 'text-purple-400' : 'text-white'}`}>
                    {team.totalWins}
                  </span>
                </div>

                {/* Win Rate */}
                <div className="col-span-2 flex items-center justify-center">
                  <span className={`font-mono font-semibold ${sortBy === 'winRate' ? 'text-purple-400' : 'text-white'}`}>
                    {winRate}%
                  </span>
                </div>
              </button>
            );
          })}
        </div>

        {/* Empty State */}
        {filteredAndSortedTeams.length === 0 && (
          <div className="py-16 text-center">
            <Trophy className="w-12 h-12 text-gray-600 mx-auto mb-4" />
            <p className="text-gray-400 mb-2">No teams found</p>
            <p className="text-sm text-gray-500">Try adjusting your filters or search query</p>
            <Button
              variant="secondary"
              onClick={() => {
                setSearchQuery('');
                setFilterLevel('all');
              }}
              className="mt-4"
            >
              Clear Filters
            </Button>
          </div>
        )}
      </div>
    </div>
  );
}