import { SlidePanelField } from "@/components/sheet/slide-panel";
import { useAuth } from "@/contexts/auth-context";
import { useUnenrolledPlayers } from "@/features/players/queries";
import { Autocomplete, Stack, Text, TextInput } from "@mantine/core";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useLingui } from "@lingui/react/macro";

interface PlayersPickerProps {
  tournamentId: string;
  value?: string[];
  onChange: (value: string[]) => void;
  disabled?: boolean;
  error?: string
}

const PlayersPicker = ({ tournamentId, value = [], onChange, disabled, error }: PlayersPickerProps) => {
  const { t } = useLingui();
  const { roles, user } = useAuth();
  const isAdmin = roles.includes("Admin");

  const { data } = useUnenrolledPlayers(tournamentId);

  const options = useMemo(() => data.filter(p => p.id != user?.id).map(p => (p.first_name + " " + p.last_name)), [data])

  const findPlayerId = useCallback((name?: string) => {
    const player = data.find(player => player?.first_name + " " + player?.last_name === name)
    return  player?.id || ""
  }, [data])

  const findPlayerName = useCallback((id?: string) => {
    const player = data.find(player => player.id === id)
    return  player?.first_name + " " + player?.last_name
  }, [data])

  const [playerOne, setPlayerOne] = useState(value.length ? findPlayerName(value[0]) : findPlayerName(user!.id));
  const [playerTwo, setPlayerTwo] = useState(value.length > 1 ? findPlayerName(value[1]) : undefined);

  useEffect(() => {
    onChange([findPlayerId(playerOne), findPlayerId(playerTwo)])
  }, [playerOne, playerTwo])

  return (
    <Stack>
      <Autocomplete
        label={t`Player 1`}
        data={options}
        disabled
        value={playerOne}
        onChange={setPlayerOne}
        comboboxProps={{ withinPortal: false }}
      />
      <Autocomplete
        label={t`Player 2`}
        data={options}
        disabled={disabled}
        value={playerTwo}
        onChange={setPlayerTwo}
        withAsterisk
        error={error}
        comboboxProps={{ withinPortal: false }}
      />
    </Stack>
  );
};

export default PlayersPicker;