import { PageWrapper } from '@/components/shared/state/PageWrapper';
import TeamsTemplate from '@/templates/TeamsTemplate';
import { PageDataFetcher } from '@/lib/page/PageDataFetcher';
import { TeamService } from '@/lib/services/teams/TeamService';
import { TeamsApiClient } from '@/lib/api/teams/TeamsApiClient';
import { EnhancedErrorReporter } from '@/lib/infrastructure/EnhancedErrorReporter';
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
import { getWebsiteApiBaseUrl } from '@/lib/config/apiBaseUrl';
import { notFound } from 'next/navigation';
import type { TeamSummaryViewModel } from '@/lib/view-models/TeamSummaryViewModel';

// Helper to compute derived data for SSR
function computeDerivedData(teams: TeamSummaryViewModel[]) {
  // Group teams by performance level (skill level)
  const teamsByLevel = teams.reduce((acc, team) => {
    const level = team.performanceLevel || 'intermediate';
    if (!acc[level]) {
      acc[level] = [];
    }
    acc[level].push(team);
    return acc;
  }, {} as Record<string, TeamSummaryViewModel[]>);

  // Get top teams (by rating, descending)
  const topTeams = [...teams]
    .filter(t => t.rating !== undefined)
    .sort((a, b) => (b.rating || 0) - (a.rating || 0))
    .slice(0, 5);

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

  // For SSR, filtered teams = all teams (no search filter applied server-side)
  const filteredTeams = teams;

  return {
    teamsByLevel,
    topTeams,
    recruitingCount,
    filteredTeams,
  };
}

// Template wrapper for SSR
function TeamsTemplateWrapper({ data }: { data: TeamSummaryViewModel[] }) {
  const derived = computeDerivedData(data);
  
  // Provide default values for SSR
  // The template will handle client-side state management
  return (
    <TeamsTemplate
      teams={data}
      isLoading={false}
      searchQuery=""
      showCreateForm={false}
      teamsByLevel={derived.teamsByLevel}
      topTeams={derived.topTeams}
      recruitingCount={derived.recruitingCount}
      filteredTeams={derived.filteredTeams}
      // No-op handlers for SSR (client will override)
      onSearchChange={() => {}}
      onShowCreateForm={() => {}}
      onHideCreateForm={() => {}}
      onTeamClick={() => {}}
      onCreateSuccess={() => {}}
      onBrowseTeams={() => {}}
      onSkillLevelClick={() => {}}
    />
  );
}

export default async function Page() {
  const data = await PageDataFetcher.fetchManual(async () => {
    // Manual dependency creation
    const baseUrl = getWebsiteApiBaseUrl();
    const logger = new ConsoleLogger();
    const errorReporter = new EnhancedErrorReporter(logger, {
      showUserNotifications: true,
      logToConsole: true,
      reportToExternal: process.env.NODE_ENV === 'production',
    });

    // Create API client
    const teamsApiClient = new TeamsApiClient(baseUrl, errorReporter, logger);

    // Create service
    const service = new TeamService(teamsApiClient);
    
    return await service.getAllTeams();
  });

  if (!data) {
    notFound();
  }

  return <PageWrapper data={data} Template={TeamsTemplateWrapper} />;
}