'use client';

import { useState, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import { Users, Search, Sparkles, Crown, Star, TrendingUp, Shield } from 'lucide-react';
import TeamsTemplate from '@/templates/TeamsTemplate';
import TeamHeroSection from '@/components/teams/TeamHeroSection';
import TeamSearchBar from '@/components/teams/TeamSearchBar';
import Card from '@/components/ui/Card';
import Button from '@/components/ui/Button';
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 type { TeamSummaryViewModel } from '@/lib/view-models/TeamSummaryViewModel';

// Shared state components
import { StateContainer } from '@/components/shared/state/StateContainer';
import { useAllTeams } from '@/hooks/team/useAllTeams';

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

const SKILL_LEVELS: SkillLevel[] = ['pro', 'advanced', 'intermediate', 'beginner'];

export default function TeamsInteractive() {
  const router = useRouter();
  
  const { data: teams = [], isLoading: loading, error, retry } = 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: [],
    };
    if (teams) {
      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(() => {
    if (!teams) return [];
    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 ? 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] ?? [];
        acc[level] = 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 ? teams.filter((t) => t.isRecruiting).length : 0;

  const handleSkillLevelClick = (level: SkillLevel) => {
    const element = document.getElementById(`level-${level}`);
    element?.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  const handleBrowseTeams = () => {
    const element = document.getElementById('teams-list');
    element?.scrollIntoView({ behavior: 'smooth' });
  };

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

  return (
    <StateContainer
      data={teams}
      isLoading={loading}
      error={error}
      retry={retry}
      config={{
        loading: { variant: 'spinner', message: 'Loading teams...' },
        error: { variant: 'full-screen' },
        empty: {
          icon: Users,
          title: 'No teams yet',
          description: 'Be the first to create a racing team. Gather drivers and compete together in endurance events.',
          action: { label: 'Create Your First Team', onClick: () => setShowCreateForm(true) }
        }
      }}
    >
      {(teamsData) => (
        <div className="max-w-7xl mx-auto px-4 pb-12">
          {/* Hero Section */}
          <TeamHeroSection
            teams={teamsData}
            teamsByLevel={teamsByLevel}
            recruitingCount={recruitingCount}
            onShowCreateForm={() => setShowCreateForm(true)}
            onBrowseTeams={handleBrowseTeams}
            onSkillLevelClick={handleSkillLevelClick}
          />

          {/* Search Bar */}
          <TeamSearchBar searchQuery={searchQuery} onSearchChange={setSearchQuery} />

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

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

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

          {/* Teams by Skill Level */}
          {teamsData.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={`level-${level}`} className="scroll-mt-8">
                  <SkillLevelSection
                    level={{
                      id: level,
                      label: level.charAt(0).toUpperCase() + level.slice(1),
                      icon: level === 'pro' ? Crown : level === 'advanced' ? Star : level === 'intermediate' ? TrendingUp : Shield,
                      color: level === 'pro' ? 'text-yellow-400' : level === 'advanced' ? 'text-purple-400' : level === 'intermediate' ? 'text-primary-blue' : 'text-green-400',
                      bgColor: level === 'pro' ? 'bg-yellow-400/10' : level === 'advanced' ? 'bg-purple-400/10' : level === 'intermediate' ? 'bg-primary-blue/10' : 'bg-green-400/10',
                      borderColor: level === 'pro' ? 'border-yellow-400/30' : level === 'advanced' ? 'border-purple-400/30' : level === 'intermediate' ? 'border-primary-blue/30' : 'border-green-400/30',
                      description: level === 'pro' ? 'Elite competition, sponsored teams' : level === 'advanced' ? 'Competitive racing, high consistency' : level === 'intermediate' ? 'Growing skills, regular practice' : 'Learning the basics, friendly environment',
                    }}
                    teams={teamsByLevel[level] ?? []}
                    onTeamClick={handleTeamClick}
                    defaultExpanded={index === 0}
                  />
                </div>
              ))}
            </div>
          )}
        </div>
      )}
    </StateContainer>
  );
}