import { PageWrapper } from '@/components/shared/state/PageWrapper';
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 { Trophy } from 'lucide-react';
import { redirect } from 'next/navigation';
import { TeamSummaryViewModel } from '@/lib/view-models/TeamSummaryViewModel';
import { TeamLeaderboardPageWrapper } from './TeamLeaderboardPageWrapper';

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

export default async function TeamLeaderboardPage() {
  // Manual wiring: create dependencies
  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 apiClient = new TeamsApiClient(baseUrl, errorReporter, logger);

  // Fetch data
  const result = await apiClient.getAll();

  // Transform DTO to ViewModel
  const teamsData: TeamSummaryViewModel[] = result.teams.map(team => new TeamSummaryViewModel(team));

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

  const hasData = (teamsData?.length ?? 0) > 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.',
      }}
    />
  );
}