'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import {
  Trophy,
  Medal,
  Crown,
  Star,
  TrendingUp,
  Shield,
  Search,
  Filter,
  Flag,
  ArrowLeft,
  Hash,
  Percent,
} from 'lucide-react';
import Button from '@/components/ui/Button';
import Input from '@/components/ui/Input';
import Heading from '@/components/ui/Heading';
import { DriversLeaderboardPresenter } from '@/lib/presenters/DriversLeaderboardPresenter';
import type { DriverLeaderboardItemViewModel, SkillLevel } from '@core/racing/application/presenters/IDriversLeaderboardPresenter';
import Image from 'next/image';

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

type SortBy = 'rank' | 'rating' | 'wins' | 'podiums' | 'winRate';

type DriverListItem = DriverLeaderboardItemViewModel;

// ============================================================================
// 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: 'rank', label: 'Rank', icon: Hash },
  { id: 'rating', label: 'Rating', icon: Star },
  { id: 'wins', label: 'Wins', icon: Trophy },
  { id: 'podiums', label: 'Podiums', icon: Medal },
  { id: 'winRate', label: 'Win Rate', icon: Percent },
];

// ============================================================================
// TOP 3 PODIUM COMPONENT
// ============================================================================

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

function TopThreePodium({ drivers, onDriverClick }: TopThreePodiumProps) {
  if (drivers.length < 3) return null;

  const top3 = drivers.slice(0, 3) as [DriverListItem, DriverListItem, DriverListItem];

  const podiumOrder: [DriverListItem, DriverListItem, DriverListItem] = [
    top3[1],
    top3[0],
    top3[2],
  ]; // 2nd, 1st, 3rd
  const podiumHeights = ['h-32', 'h-40', 'h-24'];
  const podiumColors = [
    'from-gray-400/20 to-gray-500/10 border-gray-400/40',
    'from-yellow-400/20 to-amber-500/10 border-yellow-400/40',
    'from-amber-600/20 to-amber-700/10 border-amber-600/40',
  ];
  const crownColors = ['text-gray-300', 'text-yellow-400', 'text-amber-600'];
  const positions = [2, 1, 3];

  return (
    <div className="mb-10">
      <div className="flex items-end justify-center gap-4 lg:gap-8">
        {podiumOrder.map((driver, index) => {
          const levelConfig = SKILL_LEVELS.find((l) => l.id === driver.skillLevel);
          const position = positions[index];

          return (
            <button
              key={driver.id}
              type="button"
              onClick={() => onDriverClick(driver.id)}
              className="flex flex-col items-center group"
            >
              {/* Driver Avatar & Info */}
              <div className="relative mb-4">
                {/* Crown for 1st place */}
                {position === 1 && (
                  <div className="absolute -top-6 left-1/2 -translate-x-1/2 animate-bounce">
                    <Crown className="w-8 h-8 text-yellow-400 drop-shadow-[0_0_10px_rgba(250,204,21,0.5)]" />
                  </div>
                )}

                {/* Avatar */}
                <div className={`relative ${position === 1 ? 'w-24 h-24 lg:w-28 lg:h-28' : 'w-20 h-20 lg:w-24 lg:h-24'} rounded-full overflow-hidden border-4 ${position === 1 ? 'border-yellow-400 shadow-[0_0_30px_rgba(250,204,21,0.3)]' : position === 2 ? 'border-gray-300' : 'border-amber-600'} group-hover:scale-105 transition-transform`}>
                  <Image
                    src={driver.avatarUrl}
                    alt={driver.name}
                    fill
                    className="object-cover"
                  />
                </div>

                {/* Position badge */}
                <div className={`absolute -bottom-2 left-1/2 -translate-x-1/2 w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold bg-gradient-to-br ${podiumColors[index]} border-2 ${crownColors[index]}`}>
                  {position}
                </div>
              </div>

              {/* Driver Name */}
              <p className={`text-white font-semibold ${position === 1 ? 'text-lg' : 'text-base'} group-hover:text-primary-blue transition-colors mb-1`}>
                {driver.name}
              </p>

              {/* Rating */}
              <p className={`font-mono font-bold ${position === 1 ? 'text-xl text-yellow-400' : 'text-lg text-primary-blue'}`}>
                {driver.rating.toLocaleString()}
              </p>

              {/* Stats */}
              <div className="flex items-center gap-2 text-xs text-gray-500 mt-1">
                <span className="flex items-center gap-1">
                  <Trophy className="w-3 h-3 text-performance-green" />
                  {driver.wins}
                </span>
                <span>•</span>
                <span className="flex items-center gap-1">
                  <Medal className="w-3 h-3 text-warning-amber" />
                  {driver.podiums}
                </span>
              </div>

              {/* Podium Stand */}
              <div className={`mt-4 w-28 lg:w-36 ${podiumHeights[index]} rounded-t-lg bg-gradient-to-t ${podiumColors[index]} border-t border-x flex items-end justify-center pb-4`}>
                <span className={`text-4xl lg:text-5xl font-black ${crownColors[index]}`}>
                  {position}
                </span>
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

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

export default function DriverLeaderboardPage() {
  const router = useRouter();
  const [drivers, setDrivers] = useState<DriverListItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedSkill, setSelectedSkill] = useState<'all' | SkillLevel>('all');
  const [sortBy, setSortBy] = useState<SortBy>('rank');
  const [showFilters, setShowFilters] = useState(false);

  useEffect(() => {
    const load = async () => {
      const useCase = getGetDriversLeaderboardUseCase();
      const presenter = new DriversLeaderboardPresenter();
      await useCase.execute(undefined as void, presenter);
      const viewModel = presenter.getViewModel();
      if (viewModel) {
        setDrivers(viewModel.drivers);
      }
      setLoading(false);
    };

    void load();
  }, []);

  const filteredDrivers = drivers.filter((driver) => {
    const matchesSearch = driver.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      driver.nationality.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesSkill = selectedSkill === 'all' || driver.skillLevel === selectedSkill;
    return matchesSearch && matchesSkill;
  });

  const sortedDrivers = [...filteredDrivers].sort((a, b) => {
    const rankA = Number.isFinite(a.rank) && a.rank > 0 ? a.rank : Number.POSITIVE_INFINITY;
    const rankB = Number.isFinite(b.rank) && b.rank > 0 ? b.rank : Number.POSITIVE_INFINITY;

    switch (sortBy) {
      case 'rank':
        return rankA - rankB || b.rating - a.rating || a.name.localeCompare(b.name);
      case 'rating':
        return b.rating - a.rating;
      case 'wins':
        return b.wins - a.wins;
      case 'podiums':
        return b.podiums - a.podiums;
      case 'winRate': {
        const aRate = a.racesCompleted > 0 ? a.wins / a.racesCompleted : 0;
        const bRate = b.racesCompleted > 0 ? b.wins / b.racesCompleted : 0;
        return bRate - aRate;
      }
      default:
        return 0;
    }
  });

  const handleDriverClick = (driverId: string) => {
    if (driverId.startsWith('demo-')) return;
    router.push(`/drivers/${driverId}`);
  };

  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-gradient-to-br from-yellow-400/20 to-yellow-600/10 border-yellow-400/40';
      case 2: return 'bg-gradient-to-br from-gray-300/20 to-gray-400/10 border-gray-300/40';
      case 3: 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-primary-blue border-t-transparent rounded-full animate-spin" />
            <p className="text-gray-400">Loading driver rankings...</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('/leaderboards')}
          className="flex items-center gap-2 mb-6"
        >
          <ArrowLeft className="w-4 h-4" />
          Back to Leaderboards
        </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-primary-blue/20 to-primary-blue/5 border border-primary-blue/20">
            <Trophy className="w-7 h-7 text-primary-blue" />
          </div>
          <div>
            <Heading level={1} className="text-3xl lg:text-4xl">
              Driver Leaderboard
            </Heading>
            <p className="text-gray-400">Full rankings of all drivers by performance metrics</p>
          </div>
        </div>
      </div>

      {/* Top 3 Podium */}
      {!searchQuery && sortBy === 'rank' && <TopThreePodium drivers={sortedDrivers} onDriverClick={handleDriverClick} />}

      {/* Filters */}
      <div className="mb-6 space-y-4">
        <div className="flex flex-col lg:flex-row gap-4">
          <div className="flex-1 relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-500" />
            <Input
              type="text"
              placeholder="Search drivers by name or nationality..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-11"
            />
          </div>
          <Button
            type="button"
            variant="secondary"
            onClick={() => setShowFilters(!showFilters)}
            className="lg:hidden flex items-center gap-2"
          >
            <Filter className="w-4 h-4" />
            Filters
          </Button>
        </div>

        <div className={`flex flex-wrap gap-2 ${showFilters ? 'block' : 'hidden lg:flex'}`}>
          <button
            type="button"
            onClick={() => setSelectedSkill('all')}
            className={`px-3 py-2 rounded-lg text-sm font-medium transition-all ${
              selectedSkill === 'all'
                ? 'bg-primary-blue 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={() => setSelectedSkill(level.id)}
                className={`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-all ${
                  selectedSkill === 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 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-primary-blue 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>

      {/* 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-5 lg:col-span-4">Driver</div>
          <div className="col-span-2 text-center hidden md:block">Races</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-1 text-center hidden lg:block">Podiums</div>
          <div className="col-span-2 text-center">Win Rate</div>
        </div>

        {/* Table Body */}
        <div className="divide-y divide-charcoal-outline/50">
          {sortedDrivers.map((driver, index) => {
            const levelConfig = SKILL_LEVELS.find((l) => l.id === driver.skillLevel);
            const LevelIcon = levelConfig?.icon || Shield;
            const winRate = driver.racesCompleted > 0 ? ((driver.wins / driver.racesCompleted) * 100).toFixed(1) : '0.0';
            const position = index + 1;

            return (
              <button
                key={driver.id}
                type="button"
                onClick={() => handleDriverClick(driver.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(position)} ${getMedalColor(position)}`}>
                    {position <= 3 ? <Medal className="w-4 h-4" /> : position}
                  </div>
                </div>

                {/* Driver Info */}
                <div className="col-span-5 lg:col-span-4 flex items-center gap-3">
                  <div className="relative w-10 h-10 rounded-full overflow-hidden border-2 border-charcoal-outline">
                    <Image src={driver.avatarUrl} alt={driver.name} fill className="object-cover" />
                  </div>
                  <div className="min-w-0">
                    <p className="text-white font-semibold truncate group-hover:text-primary-blue transition-colors">
                      {driver.name}
                    </p>
                    <div className="flex items-center gap-2 text-xs text-gray-500">
                      <span className="flex items-center gap-1">
                        <Flag className="w-3 h-3" />
                        {driver.nationality}
                      </span>
                      <span className={`flex items-center gap-1 ${levelConfig?.color}`}>
                        <LevelIcon className="w-3 h-3" />
                        {levelConfig?.label}
                      </span>
                    </div>
                  </div>
                </div>

                {/* Races */}
                <div className="col-span-2 items-center justify-center hidden md:flex">
                  <span className="text-gray-400">{driver.racesCompleted}</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-primary-blue' : 'text-white'}`}>
                    {driver.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-primary-blue' : 'text-performance-green'}`}>
                    {driver.wins}
                  </span>
                </div>

                {/* Podiums */}
                <div className="col-span-1 items-center justify-center hidden lg:flex">
                  <span className={`font-mono font-semibold ${sortBy === 'podiums' ? 'text-primary-blue' : 'text-warning-amber'}`}>
                    {driver.podiums}
                  </span>
                </div>

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

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