'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 { PageHeader } from '@/ui/PageHeader';
import { Button } from '@/ui/Button';
import { EmptyState } from '@/ui/EmptyState';
import { Container } from '@/ui/Container';
import { Section } from '@/ui/Section';
import { Stack } from '@/ui/Stack';
import { Carousel } from '@/components/shared/Carousel';

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.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) => b.ratingValue - a.ratingValue)
      .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 (
    <Section variant="default" padding="md">
      <PageHeader
        title="Teams"
        description="Professional racing organizations and community teams."
        icon={Users}
        action={
          <Button 
            variant="secondary" 
            onClick={onViewFullLeaderboard}
          >
            Leaderboard
          </Button>
        }
      />

      <Stack gap={12}>
        <TeamSearchBar 
          searchQuery={searchQuery} 
          onSearchChange={onSearchChange} 
        />

        {clusters.length > 0 ? (
          <Stack gap={12}>
            {clusters.map((cluster) => (
              <Carousel 
                key={cluster.title}
                title={cluster.title} 
                count={cluster.teams.length}
              >
                {cluster.teams.map((team) => (
                  <TeamCard
                    key={team.teamId}
                    team={team}
                    onClick={(id) => onTeamClick?.(id)}
                  />
                ))}
              </Carousel>
            ))}
          </Stack>
        ) : (
          <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'
            }}
          />
        )}
      </Stack>
    </Section>
  );
}
