import type { Socket } from 'socket.io-client'
import { createSharedComposable } from '@vueuse/core'
import { io } from 'socket.io-client'

export const useSignaling = createSharedComposable(() => {
  const toast = useToast()
  const { me } = useAuth()

  const socket = shallowRef<Socket>()

  const connected = ref(false)

  watch(socket, (socket, prevSocket) => {
    if (prevSocket) {
      prevSocket.close()
    }

    if (!socket) {
      return
    }

    if (import.meta.dev) {
      socket.onAny((event, ...args) => {
        console.info('[onAny]', event, args)
      })

      socket.onAnyOutgoing((event, ...args) => {
        console.info('[onAnyOutgoing]', event, args)
      })
    }

    socket.on('connect', async () => {
      connected.value = true
    })

    socket.on('disconnect', async () => {
      connected.value = false
    })
  }, { immediate: true, flush: 'sync' })

  watch(connected, (connected) => {
    if (connected)
      toast.add({ severity: 'success', summary: 'Connected', closable: false, life: 1000 })
    else
      toast.add({ severity: 'error', summary: 'Disconnected', closable: false, life: 1000 })
  }, { immediate: true })

  watch(me, (me) => {
    if (!me) {
      socket.value?.close()
      socket.value = undefined
    }
  })

  onScopeDispose(() => {
    socket.value?.close()
    socket.value = undefined
  })

  function connect() {
    if (socket.value)
      return

    socket.value = io('https://api.koptilnya.xyz/webrtc', {
    // socket.value = io('http://localhost:4000/webrtc', {
      path: '/chad/ws',
      transports: ['websocket'],
      withCredentials: true,
      auth: {
        userId: me.value!.id,
      },
    })
  }

  return {
    socket,
    connected,
    connect,
  }
})
