'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import {
  Users,
  Trophy,
  Search,
  Plus,
  Sparkles,
  Crown,
  Star,
  TrendingUp,
  Shield,
  Zap,
  UserPlus,
  ChevronRight,
  Timer,
  Target,
  Award,
  Handshake,
  MessageCircle,
  Calendar,
} from 'lucide-react';
import TeamCard from '@/components/teams/TeamCard';
import Button from '@/components/ui/Button';
import Card from '@/components/ui/Card';
import Input from '@/components/ui/Input';
import Heading from '@/components/ui/Heading';
import CreateTeamForm from '@/components/teams/CreateTeamForm';
import { TeamsLeaderboardPresenter } from '@/lib/presenters/TeamsLeaderboardPresenter';
import type { TeamLeaderboardItemViewModel, SkillLevel } from '@core/racing/application/presenters/ITeamsLeaderboardPresenter';

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

type TeamDisplayData = TeamLeaderboardItemViewModel;

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

const SKILL_LEVELS: {
  id: SkillLevel;
  label: string;
  icon: React.ElementType;
  color: string;
  bgColor: string;
  borderColor: string;
  description: string;
}[] = [
  {
    id: 'pro',
    label: 'Pro',
    icon: Crown,
    color: 'text-yellow-400',
    bgColor: 'bg-yellow-400/10',
    borderColor: 'border-yellow-400/30',
    description: 'Elite competition, sponsored teams',
  },
  {
    id: 'advanced',
    label: 'Advanced',
    icon: Star,
    color: 'text-purple-400',
    bgColor: 'bg-purple-400/10',
    borderColor: 'border-purple-400/30',
    description: 'Competitive racing, high consistency',
  },
  {
    id: 'intermediate',
    label: 'Intermediate',
    icon: TrendingUp,
    color: 'text-primary-blue',
    bgColor: 'bg-primary-blue/10',
    borderColor: 'border-primary-blue/30',
    description: 'Growing skills, regular practice',
  },
  {
    id: 'beginner',
    label: 'Beginner',
    icon: Shield,
    color: 'text-green-400',
    bgColor: 'bg-green-400/10',
    borderColor: 'border-green-400/30',
    description: 'Learning the basics, friendly environment',
  },
];

// ============================================================================
// WHY JOIN A TEAM SECTION
// ============================================================================

function WhyJoinTeamSection() {
  const benefits = [
    {
      icon: Handshake,
      title: 'Shared Strategy',
      description: 'Develop setups together, share telemetry, and coordinate pit strategies for endurance races.',
    },
    {
      icon: MessageCircle,
      title: 'Team Communication',
      description: 'Discord integration, voice chat during races, and dedicated team channels.',
    },
    {
      icon: Calendar,
      title: 'Coordinated Schedule',
      description: 'Team calendars, practice sessions, and organized race attendance.',
    },
    {
      icon: Trophy,
      title: 'Team Championships',
      description: 'Compete in team-based leagues and build your collective reputation.',
    },
  ];

  return (
    <div className="mb-12">
      <div className="text-center mb-8">
        <h2 className="text-2xl font-bold text-white mb-2">Why Join a Team?</h2>
        <p className="text-gray-400">Racing is better when you have teammates to share the journey</p>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        {benefits.map((benefit) => (
          <div
            key={benefit.title}
            className="p-5 rounded-xl bg-iron-gray/50 border border-charcoal-outline/50 hover:border-purple-500/30 transition-all duration-300"
          >
            <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-purple-500/10 border border-purple-500/20 mb-3">
              <benefit.icon className="w-5 h-5 text-purple-400" />
            </div>
            <h3 className="text-white font-semibold mb-1">{benefit.title}</h3>
            <p className="text-sm text-gray-500">{benefit.description}</p>
          </div>
        ))}
      </div>
    </div>
  );
}

// ============================================================================
// SKILL LEVEL SECTION COMPONENT
// ============================================================================

interface SkillLevelSectionProps {
  level: typeof SKILL_LEVELS[0];
  teams: TeamDisplayData[];
  onTeamClick: (id: string) => void;
  defaultExpanded?: boolean;
}

function SkillLevelSection({ level, teams, onTeamClick, defaultExpanded = false }: SkillLevelSectionProps) {
  const [isExpanded, setIsExpanded] = useState(defaultExpanded);
  const recruitingTeams = teams.filter((t) => t.isRecruiting);
  const displayedTeams = isExpanded ? teams : teams.slice(0, 3);
  const Icon = level.icon;

  if (teams.length === 0) return null;

  return (
    <div className="mb-8">
      {/* Section Header */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-3">
          <div className={`flex h-11 w-11 items-center justify-center rounded-xl ${level.bgColor} border ${level.borderColor}`}>
            <Icon className={`w-5 h-5 ${level.color}`} />
          </div>
          <div>
            <div className="flex items-center gap-2">
              <h2 className="text-xl font-bold text-white">{level.label}</h2>
              <span className="px-2 py-0.5 rounded-full text-xs bg-charcoal-outline/50 text-gray-400">
                {teams.length} {teams.length === 1 ? 'team' : 'teams'}
              </span>
              {recruitingTeams.length > 0 && (
                <span className="flex items-center gap-1 px-2 py-0.5 rounded-full text-xs bg-performance-green/10 text-performance-green border border-performance-green/20">
                  <UserPlus className="w-3 h-3" />
                  {recruitingTeams.length} recruiting
                </span>
              )}
            </div>
            <p className="text-sm text-gray-500">{level.description}</p>
          </div>
        </div>

        {teams.length > 3 && (
          <button
            type="button"
            onClick={() => setIsExpanded(!isExpanded)}
            className="flex items-center gap-1 px-3 py-1.5 rounded-lg text-sm text-gray-400 hover:text-white hover:bg-iron-gray/50 transition-all"
          >
            {isExpanded ? 'Show less' : `View all ${teams.length}`}
            <ChevronRight className={`w-4 h-4 transition-transform ${isExpanded ? 'rotate-90' : ''}`} />
          </button>
        )}
      </div>

      {/* Teams Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {displayedTeams.map((team) => (
          <TeamCard
            key={team.id}
            id={team.id}
            name={team.name}
            description={team.description ?? ''}
            memberCount={team.memberCount}
            rating={team.rating}
            totalWins={team.totalWins}
            totalRaces={team.totalRaces}
            performanceLevel={team.performanceLevel}
            isRecruiting={team.isRecruiting}
            specialization={team.specialization}
            region={team.region ?? ''}
            languages={team.languages}
            onClick={() => onTeamClick(team.id)}
          />
        ))}
      </div>
    </div>
  );
}

// ============================================================================
// FEATURED RECRUITING TEAMS
// ============================================================================

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

function FeaturedRecruiting({ teams, onTeamClick }: FeaturedRecruitingProps) {
  const recruitingTeams = teams.filter((t) => t.isRecruiting).slice(0, 4);

  if (recruitingTeams.length === 0) return null;

  return (
    <div className="mb-10">
      <div className="flex items-center gap-3 mb-4">
        <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-performance-green/10 border border-performance-green/20">
          <UserPlus className="w-5 h-5 text-performance-green" />
        </div>
        <div>
          <h2 className="text-lg font-semibold text-white">Looking for Drivers</h2>
          <p className="text-xs text-gray-500">Teams actively recruiting new members</p>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        {recruitingTeams.map((team) => {
          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="p-4 rounded-xl bg-iron-gray/60 border border-charcoal-outline hover:border-performance-green/40 transition-all duration-200 text-left group"
            >
              <div className="flex items-start justify-between mb-3">
                <div className={`flex h-8 w-8 items-center justify-center rounded-lg ${levelConfig?.bgColor} border ${levelConfig?.borderColor}`}>
                  <LevelIcon className={`w-4 h-4 ${levelConfig?.color}`} />
                </div>
                <span className="flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] bg-performance-green/10 text-performance-green border border-performance-green/20">
                  <div className="w-1.5 h-1.5 rounded-full bg-performance-green animate-pulse" />
                  Recruiting
                </span>
              </div>

              <h3 className="text-white font-semibold mb-1 group-hover:text-performance-green transition-colors line-clamp-1">
                {team.name}
              </h3>
              <p className="text-xs text-gray-500 line-clamp-2 mb-3">{team.description}</p>

              <div className="flex items-center gap-3 text-xs text-gray-400">
                <span className="flex items-center gap-1">
                  <Users className="w-3 h-3" />
                  {team.memberCount}
                </span>
                <span className="flex items-center gap-1">
                  <Trophy className="w-3 h-3" />
                  {team.totalWins} wins
                </span>
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ============================================================================
// TEAM LEADERBOARD PREVIEW COMPONENT (Top 5 + Link)
// ============================================================================

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

function TeamLeaderboardPreview({ topTeams, onTeamClick }: TeamLeaderboardPreviewProps) {
  const router = useRouter();

  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-yellow-400/10 border-yellow-400/30';
      case 1:
        return 'bg-gray-300/10 border-gray-300/30';
      case 2:
        return 'bg-amber-600/10 border-amber-600/30';
      default:
        return 'bg-iron-gray/50 border-charcoal-outline';
    }
  };

  if (topTeams.length === 0) return null;

  return (
    <div className="mb-12">
      {/* Header */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-3">
          <div className="flex h-11 w-11 items-center justify-center rounded-xl bg-gradient-to-br from-yellow-400/20 to-amber-600/10 border border-yellow-400/30">
            <Award className="w-5 h-5 text-yellow-400" />
          </div>
          <div>
            <h2 className="text-xl font-bold text-white">Top Teams</h2>
            <p className="text-sm text-gray-500">Highest rated racing teams</p>
          </div>
        </div>

        <Button
          variant="secondary"
          onClick={() => router.push('/teams/leaderboard')}
          className="flex items-center gap-2 text-sm"
        >
          View Full Leaderboard
          <ChevronRight className="w-4 h-4" />
        </Button>
      </div>

      {/* Compact Leaderboard */}
      <div className="rounded-xl bg-iron-gray/30 border border-charcoal-outline overflow-hidden">
        <div className="divide-y divide-charcoal-outline/50">
          {topTeams.map((team, 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 items-center gap-4 px-4 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(index)} ${getMedalColor(index)}`}
                >
                  {index < 3 ? (
                    <Crown className="w-3.5 h-3.5" />
                  ) : (
                    index + 1
                  )}
                </div>

                {/* Team Info */}
                <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>
                <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-3 text-xs text-gray-500">
                    <span className="flex items-center gap-1">
                      <Users className="w-3 h-3" />
                      {team.memberCount}
                    </span>
                    <span className="flex items-center gap-1">
                      <Trophy className="w-3 h-3" />
                      {team.totalWins} wins
                    </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>

                {/* Rating */}
                <div className="text-right">
                  <p className="text-purple-400 font-mono font-semibold">
                    {team.rating?.toLocaleString()}
                  </p>
                  <p className="text-xs text-gray-500">Rating</p>
                </div>
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

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

export default function TeamsPage() {
  const router = useRouter();
  const [realTeams, setRealTeams] = useState<TeamDisplayData[]>([]);
  const [groupsBySkillLevel, setGroupsBySkillLevel] = useState<Record<SkillLevel, TeamDisplayData[]>>({
    beginner: [],
    intermediate: [],
    advanced: [],
    pro: [],
  });
  const [topTeams, setTopTeams] = useState<TeamDisplayData[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [showCreateForm, setShowCreateForm] = useState(false);

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

  const loadTeams = async () => {
    try {
      const useCase = getGetTeamsLeaderboardUseCase();
      const presenter = new TeamsLeaderboardPresenter();

      await useCase.execute(undefined as void, presenter);

      const viewModel = presenter.getViewModel();
      if (viewModel) {
        setRealTeams(viewModel.teams);
        setGroupsBySkillLevel(viewModel.groupsBySkillLevel);
        setTopTeams(viewModel.topTeams);
      }
    } 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}`);
  };

  const handleCreateSuccess = (teamId: string) => {
    setShowCreateForm(false);
    void loadTeams();
    router.push(`/teams/${teamId}`);
  };

  // Filter by search query
  const filteredTeams = teams.filter((team) => {
    if (!searchQuery) return true;
    const query = searchQuery.toLowerCase();
    return (
      team.name.toLowerCase().includes(query) ||
      (team.description ?? '').toLowerCase().includes(query) ||
      (team.region ?? '').toLowerCase().includes(query) ||
      (team.languages ?? []).some((lang) => lang.toLowerCase().includes(query))
    );
  });

  // Group teams by skill level
  const teamsByLevel: Record<SkillLevel, TeamDisplayData[]> = SKILL_LEVELS.reduce(
    (acc, level) => {
      const fromGroup = groupsBySkillLevel[level.id] ?? [];
      acc[level.id] = filteredTeams.filter((team) =>
        fromGroup.some((groupTeam) => groupTeam.id === team.id),
      );
      return acc;
    },
    {
      beginner: [],
      intermediate: [],
      advanced: [],
      pro: [],
    } as Record<SkillLevel, TeamDisplayData[]>,
  );

  const recruitingCount = teams.filter((t) => t.isRecruiting).length;

  if (showCreateForm) {
    return (
      <div className="max-w-4xl mx-auto px-4">
        <div className="mb-6">
          <Button variant="secondary" onClick={() => setShowCreateForm(false)}>
            ← Back to Teams
          </Button>
        </div>

        <Card>
          <h2 className="text-2xl font-bold text-white mb-6">Create New Team</h2>
          <CreateTeamForm onCancel={() => setShowCreateForm(false)} onSuccess={handleCreateSuccess} />
        </Card>
      </div>
    );
  }

  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-purple-400 border-t-transparent rounded-full animate-spin" />
            <p className="text-gray-400">Loading teams...</p>
          </div>
        </div>
      </div>
    );
  }

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

          <div className="relative z-10">
            <div className="flex flex-col lg:flex-row lg:items-start lg:justify-between gap-8">
              <div className="max-w-xl">
                {/* Badge */}
                <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-purple-500/10 border border-purple-500/20 text-purple-400 text-xs font-medium mb-4">
                  <Users className="w-3.5 h-3.5" />
                  Team Racing
                </div>

                <Heading level={1} className="text-4xl lg:text-5xl mb-4">
                  Find Your
                  <span className="text-purple-400"> Crew</span>
                </Heading>

                <p className="text-gray-400 text-lg leading-relaxed mb-6">
                  Solo racing is great. Team racing is unforgettable. Join a team that matches your skill level and ambitions.
                </p>

                {/* Quick Stats */}
                <div className="flex flex-wrap gap-4 mb-6">
                  <div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-iron-gray/50 border border-charcoal-outline">
                    <Users className="w-4 h-4 text-purple-400" />
                    <span className="text-white font-semibold">{teams.length}</span>
                    <span className="text-gray-500 text-sm">Teams</span>
                  </div>
                  <div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-iron-gray/50 border border-charcoal-outline">
                    <UserPlus className="w-4 h-4 text-performance-green" />
                    <span className="text-white font-semibold">{recruitingCount}</span>
                    <span className="text-gray-500 text-sm">Recruiting</span>
                  </div>
                </div>

                {/* CTA Buttons */}
                <div className="flex flex-wrap gap-3">
                  <Button
                    variant="primary"
                    onClick={() => setShowCreateForm(true)}
                    className="flex items-center gap-2 px-5 py-2.5 bg-purple-600 hover:bg-purple-500"
                  >
                    <Plus className="w-4 h-4" />
                    Create Team
                  </Button>
                  <Button
                    variant="secondary"
                    onClick={() => {
                      const element = document.getElementById('teams-list');
                      element?.scrollIntoView({ behavior: 'smooth' });
                    }}
                    className="flex items-center gap-2"
                  >
                    <Search className="w-4 h-4" />
                    Browse Teams
                  </Button>
                </div>
              </div>

              {/* Skill Level Quick Nav */}
              <div className="lg:w-72">
                <p className="text-xs text-gray-500 uppercase tracking-wider mb-3">Find Your Level</p>
                <div className="space-y-2">
                  {SKILL_LEVELS.map((level) => {
                    const LevelIcon = level.icon;
                    const count = teamsByLevel[level.id]?.length || 0;

                    return (
                      <button
                        key={level.id}
                        type="button"
                        onClick={() => {
                          const element = document.getElementById(`level-${level.id}`);
                          element?.scrollIntoView({ behavior: 'smooth', block: 'start' });
                        }}
                        className={`w-full flex items-center justify-between p-3 rounded-lg ${level.bgColor} border ${level.borderColor} hover:scale-[1.02] transition-all duration-200`}
                      >
                        <div className="flex items-center gap-2">
                          <LevelIcon className={`w-4 h-4 ${level.color}`} />
                          <span className="text-white font-medium">{level.label}</span>
                        </div>
                        <span className="text-gray-400 text-sm">{count} teams</span>
                      </button>
                    );
                  })}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Search and Filter Bar - Same style as Leagues */}
      <div id="teams-list" className="mb-6 scroll-mt-8">
        <div className="flex flex-col lg:flex-row gap-4">
          {/* Search */}
          <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 teams by name, description, region, or language..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-11"
            />
          </div>
        </div>
      </div>

      {/* Why Join Section */}
      {!searchQuery && <WhyJoinTeamSection />}

      {/* Team Leaderboard Preview */}
      {!searchQuery && <TeamLeaderboardPreview topTeams={topTeams} onTeamClick={handleTeamClick} />}

      {/* Featured Recruiting */}
      {!searchQuery && <FeaturedRecruiting teams={teams} onTeamClick={handleTeamClick} />}

      {/* Teams by Skill Level */}
      {teams.length === 0 ? (
        <Card className="text-center py-16">
          <div className="max-w-md mx-auto">
            <div className="flex h-16 w-16 mx-auto items-center justify-center rounded-2xl bg-purple-500/10 border border-purple-500/20 mb-6">
              <Users className="w-8 h-8 text-purple-400" />
            </div>
            <Heading level={2} className="text-2xl mb-3">
              No teams yet
            </Heading>
            <p className="text-gray-400 mb-8">
              Be the first to create a racing team. Gather drivers and compete together in endurance events.
            </p>
            <Button
              variant="primary"
              onClick={() => setShowCreateForm(true)}
              className="flex items-center gap-2 mx-auto bg-purple-600 hover:bg-purple-500"
            >
              <Sparkles className="w-4 h-4" />
              Create Your First Team
            </Button>
          </div>
        </Card>
      ) : filteredTeams.length === 0 ? (
        <Card className="text-center py-12">
          <div className="flex flex-col items-center gap-4">
            <Search className="w-10 h-10 text-gray-600" />
            <p className="text-gray-400">No teams found matching "{searchQuery}"</p>
            <Button variant="secondary" onClick={() => setSearchQuery('')}>
              Clear search
            </Button>
          </div>
        </Card>
      ) : (
        <div>
          {SKILL_LEVELS.map((level, index) => (
            <div key={level.id} id={`level-${level.id}`} className="scroll-mt-8">
              <SkillLevelSection
                level={level}
                teams={teamsByLevel[level.id]}
                onTeamClick={handleTeamClick}
                defaultExpanded={index === 0}
              />
            </div>
          ))}
        </div>
      )}
    </div>
  );
}