'use client';

import { useState, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import type { TeamsPageDto } from '@/lib/page-queries/page-queries/TeamsPageQuery';
import { TeamsPresenter } from '@/lib/presenters/TeamsPresenter';
import { TeamsTemplate } from '@/templates/TeamsTemplate';
import type { TeamSummaryData } from '@/templates/view-data/TeamsViewData';

interface TeamsPageClientProps {
  pageDto: TeamsPageDto;
}

export function TeamsPageClient({ pageDto }: TeamsPageClientProps) {
  const router = useRouter();
  
  // Use presenter to create ViewData
  const viewData = TeamsPresenter.createViewData(pageDto);
  
  // UI state
  const [searchQuery, setSearchQuery] = useState('');
  const [showCreateForm, setShowCreateForm] = useState(false);
  
  // Filter teams based on search query
  const filteredTeams = useMemo(() => {
    if (!searchQuery) return viewData.teams;
    
    const query = searchQuery.toLowerCase();
    return viewData.teams.filter((team: TeamSummaryData) =>
      team.teamName.toLowerCase().includes(query) ||
      team.leagueName.toLowerCase().includes(query)
    );
  }, [viewData.teams, searchQuery]);
  
  // Update viewData with filtered teams
  const templateViewData = {
    ...viewData,
    teams: filteredTeams,
  };
  
  // Event handlers
  const handleSearchChange = (query: string) => {
    setSearchQuery(query);
  };
  
  const handleShowCreateForm = () => {
    setShowCreateForm(true);
  };
  
  const handleHideCreateForm = () => {
    setShowCreateForm(false);
  };
  
  const handleTeamClick = (teamId: string) => {
    router.push(`/teams/${teamId}`);
  };
  
  const handleCreateSuccess = (teamId: string) => {
    setShowCreateForm(false);
    router.push(`/teams/${teamId}`);
  };
  
  const handleBrowseTeams = () => {
    const element = document.getElementById('teams-list');
    if (element) {
      element.scrollIntoView({ behavior: 'smooth' });
    }
  };
  
  const handleSkillLevelClick = (level: string) => {
    const element = document.getElementById(`level-${level}`);
    if (element) {
      element.scrollIntoView({ behavior: 'smooth' });
    }
  };
  
  return (
    <TeamsTemplate
      teams={templateViewData.teams}
      searchQuery={searchQuery}
      showCreateForm={showCreateForm}
      onSearchChange={handleSearchChange}
      onShowCreateForm={handleShowCreateForm}
      onHideCreateForm={handleHideCreateForm}
      onTeamClick={handleTeamClick}
      onCreateSuccess={handleCreateSuccess}
      onBrowseTeams={handleBrowseTeams}
      onSkillLevelClick={handleSkillLevelClick}
    />
  );
}
