import ListButton from "@/components/list-button";
import Sheet from "@/components/sheet/sheet";
import { useSheet } from "@/hooks/use-sheet";
import { UserListIcon } from "@phosphor-icons/react";
import { useMemo } from "react";
import { useFreeAgents } from "../../queries";
import { Text } from "@mantine/core";
import PlayerList from "@/features/players/components/player-list";
import { Player } from "@/features/players/types";

interface EnrolledPlayersListButtonProps {
  tournamentId: string;
}

const EnrolledPlayersListButton: React.FC<EnrolledPlayersListButtonProps> = ({ tournamentId }) => {
  const { data: freeAgents } = useFreeAgents(tournamentId);
  const count = useMemo(() => freeAgents.length, [freeAgents]);
  const { open, isOpen, toggle } = useSheet();

  const players = useMemo(() =>
    freeAgents.map(agent => agent.player).filter((player): player is Player => player !== undefined),
    [freeAgents]
  );

  return (
    <>
      <ListButton
        label={`View Enrolled Players (${count})`}
        Icon={UserListIcon}
        onClick={open}
      />

      <Sheet title="Enrolled Players" opened={isOpen} onChange={toggle}>
        {count === 0 ? (
          <Text size="sm" c="dimmed" ta="center" py="xl">
            No players enrolled yet
          </Text>
        ) : (
          <PlayerList players={players} />
        )}
      </Sheet>
    </>
  );
};

export default EnrolledPlayersListButton;
