import { useMemo } from 'react';
import { useLingui } from '@lingui/react/macro';
import { listPlayers } from '@/features/players/server';
import { useServerSuspenseQuery } from '@/lib/tanstack-query/hooks';

export const playerKeys = {
  all: ['players'] as const,
  available: (excludedIds: string[] = []) => [...playerKeys.all, 'available', excludedIds] as const,
};

export const playerQueries = {
  all: () => ({
    queryKey: playerKeys.all,
    queryFn: listPlayers
  }),
};

export const useAvailablePlayers = (excludedPlayerIds: string[] = []) => {
  const { t } = useLingui();
  const { data: allPlayers } = useServerSuspenseQuery(playerQueries.all());

  const availablePlayers = useMemo(() => {
    if (!allPlayers) return [];

    return allPlayers.filter(player => 
      !excludedPlayerIds.includes(player.id) &&
      player.first_name &&
      player.last_name
    );
  }, [allPlayers, excludedPlayerIds]);

  const playerOptions = useMemo(() => 
    availablePlayers.map(player => ({
      value: player.id,
      label: `${player.first_name} ${player.last_name}`.trim() || t`Unnamed Player`
    })),
    [availablePlayers, t]
  );

  return {
    availablePlayers,
    playerOptions,
    allPlayers
  };
};

export const useAllPlayers = () => useServerSuspenseQuery(playerQueries.all());
