import { useCallback } from "react";
import create from "zustand";
import { persist } from "zustand/middleware";

type TeamGeneratorStore = {
  players: Array<string>;
  set: (input: Omit<Partial<TeamGeneratorStore>, "set">) => void;
  get: () => TeamGeneratorStore;
  setConfig: (config: Config) => void;
  save: boolean;
  setPlayers: (players: Array<string>) => void;
  teams: Array<Array<string>>;
  config: Config;
};

type Config = {
  teamCount: number;
};

const useTeamGeneratorStore = create(
  persist<TeamGeneratorStore>(
    (set, get) => ({
      set,
      save: false,
      get,
      setPlayers: (players) => set({ players }),
      setConfig: (config) => set({ config }),
      players: [],
      teams: [],
      config: {
        teamCount: 2,
      },
    }),
    {
      name: "team-generator-storage",
    }
  )
);

export { useTeamGeneratorStore };

export default function useTeamGenerator() {
  const { players, teams, set, config, setConfig, setPlayers, get, save } =
    useTeamGeneratorStore();

  const generate = () => {
    const store = get();

    const shuffledPlayers = [...store.players].sort(() =>
      Math.random() > 0.5 ? 1 : -1
    );

    const _teams = [];

    const range = Math.ceil(store.players.length / config.teamCount);
    while (shuffledPlayers.length > 0) {
      _teams.push(shuffledPlayers.splice(0, range));
    }

    set({ teams: _teams });

    if (!store.save) {
      localStorage.removeItem("team-generator-storage");
    }
  };

  return {
    generate,
    setConfig,
    set,
    save,
    setPlayers,
    players,
    teams,
  };
}
