import { shallowCompareKeys } from '@blueprintjs/core/lib/esm/common/utils'
import type { Team } from '@inject/graphql/fragments/Team.generated'
import Keys from '@inject/shared/localstorage/keys'
import { makeVar, useReactiveVar } from '@inject/shared/utils/reactive'

export interface TeamState {
  team: Team
  show: boolean
  inactive: boolean
}

export interface TeamStateMap {
  [teamId: string]: TeamState
}

const initialSettings: TeamStateMap = JSON.parse(
  localStorage.getItem(Keys.INSTRUCTOR_TEAMS) || '{}'
)

export const teamStateMap = makeVar<TeamStateMap>(initialSettings)
export const useTeamStateMap = () => useReactiveVar(teamStateMap)

function change(value: TeamStateMap) {
  localStorage.setItem(Keys.INSTRUCTOR_TEAMS, JSON.stringify(value))
}

window.addEventListener('storage', ({ key, newValue, oldValue }) => {
  if (key === Keys.INSTRUCTOR_TEAMS) {
    const newMap = JSON.parse(newValue || '{}')
    if (newValue !== oldValue && !shallowCompareKeys(newMap, teamStateMap())) {
      teamStateMap(newMap)
    }
  }
})

export const toggleTeam = (teamId: string) => {
  const prev = teamStateMap() as TeamStateMap
  const chosenTeam = prev[teamId]
  teamStateMap({
    ...prev,
    [teamId]: {
      ...chosenTeam,
      show: !chosenTeam.show,
    },
  })
}

export const unsetTeams = () => {
  const prev = teamStateMap() as TeamStateMap
  teamStateMap(
    Object.fromEntries(
      Object.entries(prev).map(([key, value]) => [
        key,
        { ...value, show: false },
      ])
    )
  )
}

teamStateMap.onNextChange(function onNext() {
  change(teamStateMap())
  teamStateMap.onNextChange(onNext)
})
