import { useEffect, useMemo } from 'react'
import type { ResultOf } from '../../graphql'
import { useTypedQuery } from '../../graphql'
import { GetEmailThreads, GetTeamQuestionnaires, GetTools } from '../../queries'
import { teamAction, teamQuestionnaireState } from '../../subscriptions'
import { useClient } from '../../urql/client'
import type { ActionLogPayload } from '../../urql/events'
import { useGenericActionLogEvent } from './utils'

const useActionLogSubscriptionTrainee = ({
  teamId,
  exerciseId,
}: {
  teamId: string
  exerciseId: string
}) => {
  const client = useClient()

  useTypedQuery({
    query: GetEmailThreads,
    variables: {
      teamId,
    },
    requestPolicy: 'cache-and-network',
    context: useMemo(
      () => ({
        suspense: true,
      }),
      []
    ),
  })
  useTypedQuery({
    query: GetTeamQuestionnaires,
    variables: {
      teamId,
    },
    requestPolicy: 'cache-and-network',
    context: useMemo(
      () => ({
        suspense: true,
      }),
      []
    ),
  })

  useEffect(() => {
    client.query(GetTools, {
      exerciseId,
    })
    const { unsubscribe: unsubQue } = client
      .subscription(teamQuestionnaireState, {
        teamId,
      })
      .subscribe(() => {})
    const { unsubscribe: unsubLog } = client
      .subscription<ResultOf<typeof teamAction>>(teamAction, {
        teamId,
      })
      .subscribe(e => {
        const newActionLog = e.data?.actionLogs?.actionLog
        const operation = e.data?.actionLogs?.eventType

        if (!newActionLog) {
          return
        }

        if (operation === 'CREATE') {
          window.dispatchEvent(
            new CustomEvent<ActionLogPayload>('actionLogEvent', {
              detail: {
                actionLog: newActionLog,
              },
            })
          )
        }
      })

    return () => {
      unsubLog()
      unsubQue()
    }
  }, [client, exerciseId, teamId])

  useGenericActionLogEvent()
}

export default useActionLogSubscriptionTrainee
