import create from 'zustand'
import { PointerLockControls } from '@react-three/drei'
import { Socket } from 'socket.io-client'

import { ActionName } from './3d/models/Human'

type Error = null | 'SOCKET'

export type Transform = {
  position: number[]
  rotation: number[]
  animation: ActionName
}

type userId = string

export type UserTransforms = Record<userId, Transform>

export type State = {
  pointerLockControls: PointerLockControls | undefined
  setPointerLockControls: (controls: PointerLockControls) => void
  pointerLocked: boolean
  setPointerLockStatus: (status: boolean) => void
  socket: null | Socket
  setSocket: (socket: Socket | null) => void
  error: Error
  setModalObra: (modalObra: number | null) => void
  modalObra?: number | null
  setError: (error: Error) => void
  initialTransform: null | Transform
  userTransforms: UserTransforms | null
  setUserTransforms: (userTransforms: UserTransforms) => void
  setInitialTransform: (initialTransform: Transform) => void
}

const useStore = create<State>((set) => ({
  pointerLockControls: undefined,
  pointerLocked: false,
  setPointerLockStatus: (status) => set(() => ({ pointerLocked: status })),
  setPointerLockControls: (controls) => set(() => ({ pointerLockControls: controls })),
  socket: null,
  setSocket: (socket) => set(() => ({ socket })),
  error: null,
  modelObra: null,
  initialTransform: null,
  setError: (error) => set(() => ({ error })),
  userTransforms: null,
  setUserTransforms: (userTransforms) => set(() => ({ userTransforms })),
  setInitialTransform: (initialTransform) => set(() => ({ initialTransform })),
  setModalObra: (modalObra: number | null) => set(() => ({ modalObra })),
}))

export default useStore
