import type { Exercise, Team } from '@inject/graphql/fragment-types'
import Keys from '@inject/shared/localstorage/keys'
import { makeVar, useReactiveVar } from '@inject/shared/utils/reactive'

export interface TeamState {
  team: Pick<Team, 'id' | 'name' | 'role'> & {
    exercise: Pick<Exercise, 'id' | 'name'>
  }
  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) {
  const currentValue = localStorage.getItem(Keys.INSTRUCTOR_TEAMS) || '{}'
  const newValue = JSON.stringify(value)
  if (currentValue !== newValue) {
    localStorage.setItem(Keys.INSTRUCTOR_TEAMS, newValue)
    broadcastChannel.postMessage(value)
  }
}

const broadcastChannel = new BroadcastChannel(Keys.INSTRUCTOR_TEAMS)
broadcastChannel.onmessage = event => teamStateMap(event.data)

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

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