import { Game, GameGroup } from "@/types/stellaris";
import { Dropdown } from "@nextui-org/react";
import { Dispatch, Key, SetStateAction, Suspense } from "react";
import { fetchGameGroups } from "@/components/server/fetchers";

type SelectionType = "all" | Set<Key>;

export const GameGroupSelect = (
  props: {
    game: Game,
    groups: [GameGroup[], Dispatch<SetStateAction<Array<GameGroup>>>],
    currentGroups: [GameGroup[], Dispatch<SetStateAction<Array<GameGroup>>>]
  }) => {
  const currentGame = props.game;
  const [gameGroups, setGameGroups] = props.groups;
  const [currentGameGroups, setCurrentGameGroups] = props.currentGroups;

  const changeSelection = (keys: SelectionType) => {
    if (keys != "all") {
      let newSelection: GameGroup[] = [];
      keys.forEach(key => {
        gameGroups.forEach(group => {
          if (key == group.name) {
            newSelection.push(group);
          }
        })
      });
      setCurrentGameGroups(newSelection)
    }
  }

  return (
    <>
      <Suspense>
        <DataHandler game={currentGame} groups={[gameGroups, setGameGroups]} currentGroups={[currentGameGroups, setCurrentGameGroups]} />
      </Suspense>
      <Dropdown>
        <Dropdown.Button flat color="secondary" css={{ tt: "capitalize" }}>
          {currentGameGroups.map(elem => elem.name).join(", ")}
        </Dropdown.Button>
        <Dropdown.Menu
          aria-label="Multiple selection actions"
          color="secondary"
          disallowEmptySelection
          selectionMode="multiple"
          selectedKeys={currentGameGroups.map(elem => elem.name)}
          onSelectionChange={changeSelection}
          items={gameGroups}
        >
          {gameGroups.map((item) => (
            <Dropdown.Item
              key={item.name}
              color="default"
            >
              {item.name}
            </Dropdown.Item>
          ))}
        </Dropdown.Menu>
      </Dropdown>
    </>
  )
}

const DataHandler = async (
  props: {
  game: Game,
  groups: [GameGroup[], Dispatch<SetStateAction<Array<GameGroup>>>],
  currentGroups: [GameGroup[], Dispatch<SetStateAction<Array<GameGroup>>>]
}) => {
  if (props) {
    const currentGame = props.game;
    const [gameGroups, setGameGroups] = props.groups;
    const [currentGameGroups, setCurrentGameGroups] = props.currentGroups;
  
    if (!gameGroups[0] || gameGroups[0].game_id != currentGame.id) {
      setGameGroups(await fetchGameGroups(currentGame));
    }
    else if (!currentGameGroups[0] || currentGameGroups[0].game_id != gameGroups[0].game_id) {
      setCurrentGameGroups(gameGroups);
    }
  
  }

  return <></>
}