'use client';

import React, { useMemo } from 'react';
import { Users } from 'lucide-react';
import { TemplateProps } from '@/lib/contracts/components/ComponentContracts';
import { TeamsViewData, TeamSummaryData } from '@/lib/view-data/TeamsViewData';
import { TeamsDirectoryHeader } from '@/components/teams/TeamsDirectoryHeader';
import { TeamGrid } from '@/components/teams/TeamGrid';
import { TeamCard } from '@/components/teams/TeamCard';
import { TeamSearchBar } from '@/components/teams/TeamSearchBar';
import { EmptyState } from '@/ui/EmptyState';
import { Container } from '@/ui/Container';
import { Heading } from '@/ui/Heading';
import { Text } from '@/ui/Text';

interface TeamsTemplateProps extends TemplateProps<TeamsViewData> {
  searchQuery: string;
  onSearchChange: (query: string) => void;
  onTeamClick?: (teamId: string) => void;
  onViewFullLeaderboard: () => void;
  onCreateTeam: () => void;
}

export function TeamsTemplate({ 
  viewData, 
  searchQuery,
  onSearchChange,
  onTeamClick, 
  onViewFullLeaderboard, 
  onCreateTeam 
}: TeamsTemplateProps) {
  const { teams } = viewData;

  const filteredTeams = useMemo(() => {
    return teams.filter(team => 
      team.teamName.toLowerCase().includes(searchQuery.toLowerCase()) ||
      (team.leagueName && team.leagueName.toLowerCase().includes(searchQuery.toLowerCase())) ||
      (team.region && team.region.toLowerCase().includes(searchQuery.toLowerCase()))
    );
  }, [teams, searchQuery]);

  const clusters = useMemo(() => {
    if (searchQuery) {
      return [{ title: 'Search Results', teams: filteredTeams }];
    }

    const topTeams = [...teams]
      .sort((a, b) => parseFloat(b.ratingLabel) - parseFloat(a.ratingLabel))
      .slice(0, 3);
    
    const recruitingTeams = teams.filter(t => t.isRecruiting && !topTeams.find(top => top.teamId === t.teamId));
    
    const otherTeams = teams.filter(t => 
      !topTeams.find(top => top.teamId === t.teamId) && 
      !recruitingTeams.find(r => r.teamId === t.teamId)
    );

    const result = [];
    if (topTeams.length > 0) result.push({ title: 'Top Rated Teams', teams: topTeams });
    if (recruitingTeams.length > 0) result.push({ title: 'Recruiting Now', teams: recruitingTeams });
    if (otherTeams.length > 0) result.push({ title: 'Active Rosters', teams: otherTeams });
    
    return result;
  }, [teams, filteredTeams, searchQuery]);

  return (
    <div className="min-h-screen bg-[var(--ui-color-bg-base)] py-12">
      <Container size="xl">
        <TeamsDirectoryHeader onCreateTeam={onCreateTeam} />
        
        <TeamSearchBar 
          searchQuery={searchQuery} 
          onSearchChange={onSearchChange} 
        />

        {clusters.length > 0 ? (
          <div className="space-y-16">
            {clusters.map((cluster) => (
              <div key={cluster.title} className="space-y-8">
                <div className="flex items-center gap-4">
                  <Heading level={2} weight="bold" uppercase tracking-widest size="sm">
                    {cluster.title}
                  </Heading>
                  <div className="flex-1 h-px bg-[var(--ui-color-border-muted)]" />
                  <div className="px-3 py-1 border border-[var(--ui-color-border-muted)]">
                    <Text size="xs" mono variant="low">{cluster.teams.length}</Text>
                  </div>
                </div>
                
                <TeamGrid>
                  {cluster.teams.map((team) => (
                    <TeamCard
                      key={team.teamId}
                      team={team}
                      onClick={(id) => onTeamClick?.(id)}
                    />
                  ))}
                </TeamGrid>
              </div>
            ))}
          </div>
        ) : (
          <div className="py-20 border border-dashed border-[var(--ui-color-border-muted)] flex flex-col items-center justify-center text-center">
            <EmptyState
              icon={Users}
              title={searchQuery ? "No matching teams" : "No teams yet"}
              description={searchQuery ? "Try adjusting your search filters" : "Get started by creating your first racing team"}
              action={{
                label: 'Create Team',
                onClick: onCreateTeam,
                variant: 'primary'
              }}
            />
          </div>
        )}
      </Container>
    </div>
  );
}
