'use client';

import { useState, useMemo } 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 WhyJoinTeamSection from '@/components/teams/WhyJoinTeamSection';
import SkillLevelSection from '@/components/teams/SkillLevelSection';
import FeaturedRecruiting from '@/components/teams/FeaturedRecruiting';
import TeamLeaderboardPreview from '@/components/teams/TeamLeaderboardPreview';
import { useAllTeams } from '@/hooks/useTeamService';
import type { TeamSummaryViewModel } from '@/lib/view-models/TeamSummaryViewModel';

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

type TeamDisplayData = TeamSummaryViewModel;

type SkillLevel = 'pro' | 'advanced' | 'intermediate' | 'beginner';

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





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

export default function TeamsPage() {
  const router = useRouter();
  const { data: teams = [], isLoading: loading } = useAllTeams();
  const [searchQuery, setSearchQuery] = useState('');
  const [showCreateForm, setShowCreateForm] = useState(false);

  // Derive groups by skill level from the loaded teams
  const groupsBySkillLevel = useMemo(() => {
    const byLevel: Record<string, typeof teams> = {
      beginner: [],
      intermediate: [],
      advanced: [],
      pro: [],
    };
    teams.forEach((team) => {
      const level = team.performanceLevel || 'intermediate';
      if (byLevel[level]) {
        byLevel[level].push(team);
      }
    });
    return byLevel;
  }, [teams]);

  // Select top teams by rating for the preview section
  const topTeams = useMemo(() => {
    const sortedByRating = [...teams].sort((a, b) => {
      // Rating is not currently part of TeamSummaryViewModel in this build.
      // Keep deterministic ordering by name until a rating field is exposed.
      return a.name.localeCompare(b.name);
    });
    return sortedByRating.slice(0, 5);
  }, [teams]);

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

  const handleCreateSuccess = (teamId: string) => {
    setShowCreateForm(false);
    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 = useMemo(() => {
    return 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<string, TeamSummaryViewModel[]>,
    );
  }, [groupsBySkillLevel, filteredTeams]);

  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>
  );
}
