import { PageWrapper } from '@/components/shared/state/PageWrapper';
import TeamLeaderboardTemplate from '@/templates/TeamLeaderboardTemplate';
import { PageDataFetcher } from '@/lib/page/PageDataFetcher';
import { TEAM_SERVICE_TOKEN } from '@/lib/di/tokens';
import { TeamService } from '@/lib/services/teams/TeamService';
import { Trophy } from 'lucide-react';
import { redirect , useRouter } from 'next/navigation';
import type { TeamSummaryViewModel } from '@/lib/view-models/TeamSummaryViewModel';
import { useState } from 'react';

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

type SkillLevel = 'pro' | 'advanced' | 'intermediate' | 'beginner';
type SortBy = 'rating' | 'wins' | 'winRate' | 'races';

// ============================================================================
// WRAPPER COMPONENT (Client-side state management)
// ============================================================================

function TeamLeaderboardPageWrapper({ data }: { data: TeamSummaryViewModel[] | null }) {
  const router = useRouter();
  
  // Client-side state for filtering and sorting
  const [searchQuery, setSearchQuery] = useState('');
  const [filterLevel, setFilterLevel] = useState<SkillLevel | 'all'>('all');
  const [sortBy, setSortBy] = useState<SortBy>('rating');

  if (!data || data.length === 0) {
    return null;
  }

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

  const handleBackToTeams = () => {
    router.push('/teams');
  };

  return (
    <TeamLeaderboardTemplate
      teams={data}
      searchQuery={searchQuery}
      filterLevel={filterLevel}
      sortBy={sortBy}
      onSearchChange={setSearchQuery}
      onFilterLevelChange={setFilterLevel}
      onSortChange={setSortBy}
      onTeamClick={handleTeamClick}
      onBackToTeams={handleBackToTeams}
    />
  );
}

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

export default async function TeamLeaderboardPage() {
  // Fetch data using PageDataFetcher
  const teamsData = await PageDataFetcher.fetch<TeamService, 'getAllTeams'>(
    TEAM_SERVICE_TOKEN,
    'getAllTeams'
  );

  // Prepare data for template
  const data: TeamSummaryViewModel[] | null = teamsData as TeamSummaryViewModel[] | null;

  const hasData = (teamsData as any)?.length > 0;

  // Handle loading state (should be fast since we're using async/await)
  const isLoading = false;
  const error = null;
  const retry = async () => {
    // In server components, we can't retry without a reload
    redirect('/teams/leaderboard');
  };

  return (
    <PageWrapper
      data={hasData ? data : null}
      isLoading={isLoading}
      error={error}
      retry={retry}
      Template={TeamLeaderboardPageWrapper}
      loading={{ variant: 'full-screen', message: 'Loading team leaderboard...' }}
      errorConfig={{ variant: 'full-screen' }}
      empty={{
        icon: Trophy,
        title: 'No teams found',
        description: 'There are no teams in the system yet.',
      }}
    />
  );
}