'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import {
  Trophy,
  Users,
  Crown,
  Star,
  TrendingUp,
  Shield,
  Medal,
  ChevronRight,
  Award,
  Flag,
  Target,
  Zap,
  Hash,
  Percent,
} from 'lucide-react';
import Button from '@/components/ui/Button';
import Heading from '@/components/ui/Heading';
import { getGetDriversLeaderboardUseCase, getGetTeamsLeaderboardUseCase } from '@/lib/di-container';
import { DriversLeaderboardPresenter } from '@/lib/presenters/DriversLeaderboardPresenter';
import { TeamsLeaderboardPresenter } from '@/lib/presenters/TeamsLeaderboardPresenter';
import type { DriverLeaderboardItemViewModel, SkillLevel } from '@gridpilot/racing/application/presenters/IDriversLeaderboardPresenter';
import type { TeamLeaderboardItemViewModel } from '@gridpilot/racing/application/presenters/ITeamsLeaderboardPresenter';
import Image from 'next/image';

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

type DriverListItem = DriverLeaderboardItemViewModel;

type TeamDisplayData = TeamLeaderboardItemViewModel;

// ============================================================================
// 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' },
];

// ============================================================================
// DRIVER LEADERBOARD PREVIEW
// ============================================================================

interface DriverLeaderboardPreviewProps {
  drivers: DriverListItem[];
  onDriverClick: (id: string) => void;
}

function DriverLeaderboardPreview({ drivers, onDriverClick }: DriverLeaderboardPreviewProps) {
  const router = useRouter();
  const top10 = drivers.slice(0, 10);

  const getMedalColor = (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 getMedalBg = (position: number) => {
    switch (position) {
      case 1: return 'bg-yellow-400/10 border-yellow-400/30';
      case 2: return 'bg-gray-300/10 border-gray-300/30';
      case 3: return 'bg-amber-600/10 border-amber-600/30';
      default: return 'bg-iron-gray/50 border-charcoal-outline';
    }
  };

  return (
    <div className="rounded-xl bg-iron-gray/30 border border-charcoal-outline overflow-hidden">
      {/* Header */}
      <div className="flex items-center justify-between px-5 py-4 border-b border-charcoal-outline bg-iron-gray/20">
        <div className="flex items-center gap-3">
          <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-gradient-to-br from-primary-blue/20 to-primary-blue/5 border border-primary-blue/20">
            <Trophy className="w-5 h-5 text-primary-blue" />
          </div>
          <div>
            <h3 className="text-lg font-semibold text-white">Driver Rankings</h3>
            <p className="text-xs text-gray-500">Top performers across all leagues</p>
          </div>
        </div>
        <Button
          variant="secondary"
          onClick={() => router.push('/leaderboards/drivers')}
          className="flex items-center gap-2 text-sm"
        >
          View All
          <ChevronRight className="w-4 h-4" />
        </Button>
      </div>

      {/* Leaderboard Rows */}
      <div className="divide-y divide-charcoal-outline/50">
        {top10.map((driver, index) => {
          const levelConfig = SKILL_LEVELS.find((l) => l.id === driver.skillLevel);
          const position = index + 1;

          return (
            <button
              key={driver.id}
              type="button"
              onClick={() => onDriverClick(driver.id)}
              className="flex items-center gap-4 px-5 py-3 w-full text-left hover:bg-iron-gray/30 transition-colors group"
            >
              {/* Position */}
              <div className={`flex h-8 w-8 items-center justify-center rounded-full text-xs font-bold border ${getMedalBg(position)} ${getMedalColor(position)}`}>
                {position <= 3 ? <Crown className="w-3.5 h-3.5" /> : position}
              </div>

              {/* Avatar */}
              <div className="relative w-9 h-9 rounded-full overflow-hidden border-2 border-charcoal-outline">
                <Image src={driver.avatarUrl} alt={driver.name} fill className="object-cover" />
              </div>

              {/* Info */}
              <div className="flex-1 min-w-0">
                <p className="text-white font-medium truncate group-hover:text-primary-blue transition-colors">
                  {driver.name}
                </p>
                <div className="flex items-center gap-2 text-xs text-gray-500">
                  <Flag className="w-3 h-3" />
                  {driver.nationality}
                  <span className={levelConfig?.color}>{levelConfig?.label}</span>
                </div>
              </div>

              {/* Stats */}
              <div className="flex items-center gap-4 text-sm">
                <div className="text-center">
                  <p className="text-primary-blue font-mono font-semibold">{driver.rating.toLocaleString()}</p>
                  <p className="text-[10px] text-gray-500">Rating</p>
                </div>
                <div className="text-center">
                  <p className="text-performance-green font-mono font-semibold">{driver.wins}</p>
                  <p className="text-[10px] text-gray-500">Wins</p>
                </div>
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ============================================================================
// TEAM LEADERBOARD PREVIEW
// ============================================================================

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

function TeamLeaderboardPreview({ teams, onTeamClick }: TeamLeaderboardPreviewProps) {
  const router = useRouter();
  const top5 = [...teams]
    .filter((t) => t.rating !== null)
    .sort((a, b) => (b.rating ?? 0) - (a.rating ?? 0))
    .slice(0, 5);

  const getMedalColor = (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 getMedalBg = (position: number) => {
    switch (position) {
      case 1: return 'bg-yellow-400/10 border-yellow-400/30';
      case 2: return 'bg-gray-300/10 border-gray-300/30';
      case 3: return 'bg-amber-600/10 border-amber-600/30';
      default: return 'bg-iron-gray/50 border-charcoal-outline';
    }
  };

  return (
    <div className="rounded-xl bg-iron-gray/30 border border-charcoal-outline overflow-hidden">
      {/* Header */}
      <div className="flex items-center justify-between px-5 py-4 border-b border-charcoal-outline bg-iron-gray/20">
        <div className="flex items-center gap-3">
          <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-gradient-to-br from-purple-500/20 to-purple-500/5 border border-purple-500/20">
            <Users className="w-5 h-5 text-purple-400" />
          </div>
          <div>
            <h3 className="text-lg font-semibold text-white">Team Rankings</h3>
            <p className="text-xs text-gray-500">Top performing racing teams</p>
          </div>
        </div>
        <Button
          variant="secondary"
          onClick={() => router.push('/teams/leaderboard')}
          className="flex items-center gap-2 text-sm"
        >
          View All
          <ChevronRight className="w-4 h-4" />
        </Button>
      </div>

      {/* Leaderboard Rows */}
      <div className="divide-y divide-charcoal-outline/50">
        {top5.map((team, index) => {
          const levelConfig = SKILL_LEVELS.find((l) => l.id === team.performanceLevel);
          const LevelIcon = levelConfig?.icon || Shield;
          const position = index + 1;

          return (
            <button
              key={team.id}
              type="button"
              onClick={() => onTeamClick(team.id)}
              className="flex items-center gap-4 px-5 py-3 w-full text-left hover:bg-iron-gray/30 transition-colors group"
            >
              {/* Position */}
              <div className={`flex h-8 w-8 items-center justify-center rounded-full text-xs font-bold border ${getMedalBg(position)} ${getMedalColor(position)}`}>
                {position <= 3 ? <Crown className="w-3.5 h-3.5" /> : position}
              </div>

              {/* Team Icon */}
              <div className={`flex h-9 w-9 items-center justify-center rounded-lg ${levelConfig?.bgColor} border ${levelConfig?.borderColor}`}>
                <LevelIcon className={`w-4 h-4 ${levelConfig?.color}`} />
              </div>

              {/* Info */}
              <div className="flex-1 min-w-0">
                <p className="text-white font-medium truncate group-hover:text-purple-400 transition-colors">
                  {team.name}
                </p>
                <div className="flex items-center gap-2 text-xs text-gray-500">
                  <Users className="w-3 h-3" />
                  {team.memberCount} members
                  <span className={levelConfig?.color}>{levelConfig?.label}</span>
                </div>
              </div>

              {/* Stats */}
              <div className="flex items-center gap-4 text-sm">
                <div className="text-center">
                  <p className="text-purple-400 font-mono font-semibold">{team.rating?.toLocaleString()}</p>
                  <p className="text-[10px] text-gray-500">Rating</p>
                </div>
                <div className="text-center">
                  <p className="text-performance-green font-mono font-semibold">{team.totalWins}</p>
                  <p className="text-[10px] text-gray-500">Wins</p>
                </div>
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

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

export default function LeaderboardsPage() {
  const router = useRouter();
  const [drivers, setDrivers] = useState<DriverListItem[]>([]);
  const [teams, setTeams] = useState<TeamDisplayData[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const load = async () => {
      try {
        const driversUseCase = getGetDriversLeaderboardUseCase();
        const teamsUseCase = getGetTeamsLeaderboardUseCase();
        const driversPresenter = new DriversLeaderboardPresenter();
        const teamsPresenter = new TeamsLeaderboardPresenter();

        await driversUseCase.execute(undefined as void, driversPresenter);
        await teamsUseCase.execute(undefined as void, teamsPresenter);

        const driversViewModel = driversPresenter.getViewModel();
        const teamsViewModel = teamsPresenter.getViewModel();

        setDrivers(driversViewModel?.drivers ?? []);
        setTeams(teamsViewModel ? teamsViewModel.teams : []);
      } catch (error) {
        console.error('Failed to load leaderboard data:', error);
        setDrivers([]);
        setTeams([]);
      } finally {
        setLoading(false);
      }
    };

    void load();
  }, []);

  const handleDriverClick = (driverId: string) => {
    router.push(`/drivers/${driverId}`);
  };

  const handleTeamClick = (teamId: string) => {
    router.push(`/teams/${teamId}`);
  };

  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 leaderboards...</p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-7xl mx-auto px-4 pb-12">
      {/* Hero Section */}
      <div className="relative mb-10 py-10 px-8 rounded-2xl bg-gradient-to-br from-yellow-600/20 via-iron-gray/80 to-deep-graphite border border-yellow-500/20 overflow-hidden">
        {/* Background decoration */}
        <div className="absolute top-0 right-0 w-96 h-96 bg-yellow-400/10 rounded-full blur-3xl" />
        <div className="absolute bottom-0 left-0 w-64 h-64 bg-amber-600/5 rounded-full blur-3xl" />
        <div className="absolute top-1/2 right-1/4 w-48 h-48 bg-purple-500/5 rounded-full blur-2xl" />

        <div className="relative z-10">
          <div className="flex items-center gap-4 mb-4">
            <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">
                Leaderboards
              </Heading>
              <p className="text-gray-400">Where champions rise and legends are made</p>
            </div>
          </div>

          <p className="text-gray-400 text-lg leading-relaxed max-w-2xl mb-6">
            Track the best drivers and teams across all competitions. Every race counts. Every position matters. Who will claim the throne?
          </p>

          {/* Quick Nav */}
          <div className="flex flex-wrap gap-3">
            <Button
              variant="secondary"
              onClick={() => router.push('/leaderboards/drivers')}
              className="flex items-center gap-2"
            >
              <Trophy className="w-4 h-4 text-primary-blue" />
              Driver Rankings
            </Button>
            <Button
              variant="secondary"
              onClick={() => router.push('/teams/leaderboard')}
              className="flex items-center gap-2"
            >
              <Users className="w-4 h-4 text-purple-400" />
              Team Rankings
            </Button>
          </div>
        </div>
      </div>

      {/* Leaderboard Grids */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <DriverLeaderboardPreview drivers={drivers} onDriverClick={handleDriverClick} />
        <TeamLeaderboardPreview teams={teams} onTeamClick={handleTeamClick} />
      </div>
    </div>
  );
}