'use client';

import { useRouter } from 'next/navigation';
import { TeamLeaderboardTemplate } from '@/templates/TeamLeaderboardTemplate';
import { useState } from 'react';
import type { TeamSummaryViewModel } from '@/lib/view-models/TeamSummaryViewModel';
import { ClientWrapperProps } from '@/lib/contracts/components/ComponentContracts';
import { ViewData } from '@/lib/contracts/view-data/ViewData';

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

interface TeamLeaderboardViewData extends ViewData {
  teams: TeamSummaryViewModel[];
}

export function TeamLeaderboardPageWrapper({ viewData }: ClientWrapperProps<TeamLeaderboardViewData>) {
  const router = useRouter();
  
  // Client-side UI state only (no business logic)
  const [searchQuery, setSearchQuery] = useState('');
  const [filterLevel, setFilterLevel] = useState<SkillLevel | 'all'>('all');
  const [sortBy, setSortBy] = useState<SortBy>('rating');

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

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

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

  // Apply filtering and sorting
  const filteredAndSortedTeams = viewData.teams
    .filter((team) => {
      const matchesSearch = team.name.toLowerCase().includes(searchQuery.toLowerCase());
      const matchesLevel = filterLevel === 'all' || team.performanceLevel === filterLevel;
      return matchesSearch && matchesLevel;
    })
    .sort((a, b) => {
      if (sortBy === 'rating') return (b.rating || 0) - (a.rating || 0);
      if (sortBy === 'wins') return b.totalWins - a.totalWins;
      if (sortBy === 'winRate') {
        const rateA = a.totalRaces > 0 ? a.totalWins / a.totalRaces : 0;
        const rateB = b.totalRaces > 0 ? b.totalWins / b.totalRaces : 0;
        return rateB - rateA;
      }
      if (sortBy === 'races') return b.totalRaces - a.totalRaces;
      return 0;
    });

  const templateViewData = {
    teams: viewData.teams,
    searchQuery,
    filterLevel,
    sortBy,
    filteredAndSortedTeams,
  };

  return (
    <TeamLeaderboardTemplate
      viewData={templateViewData}
      onSearchChange={setSearchQuery}
      filterLevelChange={setFilterLevel}
      onSortChange={setSortBy}
      onTeamClick={handleTeamClick}
      onBackToTeams={handleBackToTeams}
    />
  );
}
