'use client';

import React, { useState, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import { TeamRankingsTemplate } from '@/templates/TeamRankingsTemplate';
import { routes } from '@/lib/routing/RouteConfig';
import type { TeamRankingsViewData } from '@/lib/view-data/TeamRankingsViewData';
import { ClientWrapperProps } from '@/lib/contracts/components/ComponentContracts';

export function TeamRankingsPageClient({ viewData }: ClientWrapperProps<TeamRankingsViewData>) {
  const router = useRouter();
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedSkill, setSelectedSkill] = useState<'all' | 'pro' | 'advanced' | 'intermediate' | 'beginner'>('all');
  const [sortBy, setSortBy] = useState<'rank' | 'rating' | 'wins' | 'memberCount'>('rank');
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 20;

  const handleTeamClick = (id: string) => {
    router.push(routes.team.detail(id));
  };

  const handleBackToLeaderboards = () => {
    router.push(routes.leaderboards.root);
  };

  const filteredAndSortedTeams = useMemo(() => {
    let result = [...viewData.teams];

    // Search
    if (searchQuery) {
      result = result.filter(team => 
        team.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
        team.tag.toLowerCase().includes(searchQuery.toLowerCase())
      );
    }

    // Skill Filter
    if (selectedSkill !== 'all') {
      result = result.filter(team => team.performanceLevel.toLowerCase() === selectedSkill);
    }

    // Sorting
    result.sort((a, b) => {
      switch (sortBy) {
        case 'rating': return (b.rating || 0) - (a.rating || 0);
        case 'wins': return b.totalWins - a.totalWins;
        case 'memberCount': return b.memberCount - a.memberCount;
        case 'rank':
        default: return a.position - b.position;
      }
    });

    return result;
  }, [viewData.teams, searchQuery, selectedSkill, sortBy]);

  const paginatedTeams = useMemo(() => {
    const startIndex = (currentPage - 1) * itemsPerPage;
    return filteredAndSortedTeams.slice(startIndex, startIndex + itemsPerPage);
  }, [filteredAndSortedTeams, currentPage]);

  const totalPages = Math.ceil(filteredAndSortedTeams.length / itemsPerPage);

  return (
    <TeamRankingsTemplate
      viewData={{
        ...viewData,
        teams: paginatedTeams,
        searchQuery,
        selectedSkill,
        sortBy,
        showFilters: false,
      }}
      onSearchChange={setSearchQuery}
      onSkillChange={setSelectedSkill}
      onSortChange={setSortBy}
      onPageChange={setCurrentPage}
      currentPage={currentPage}
      totalPages={totalPages}
      totalTeams={filteredAndSortedTeams.length}
      onTeamClick={handleTeamClick}
      onBackToLeaderboards={handleBackToLeaderboards}
    />
  );
}
