import { useEffect, useMemo } from 'react'
import { useQuery } from 'urql'
import {
  GetAnalyticsEmailThreads,
  GetAnalyticsMilestones,
  GetTools,
} from '../../queries'
import { exerciseActionLogs, exerciseMilestones } from '../../subscriptions'
import { useClient } from '../../urql/client'
import type { ActionLogPayload } from '../../urql/events'
import useExerciseLoopStatusSubscription from '../useExerciseLoopStatusSubscription'
import { useGenericActionLogEvent } from './utils'

const useActionLogSubscriptionInstructor = ({
  exerciseId,
}: {
  exerciseId: string
}) => {
  const client = useClient()
  useExerciseLoopStatusSubscription(exerciseId)

  useQuery({
    query: GetAnalyticsEmailThreads,
    variables: {
      exerciseId,
    },
    requestPolicy: 'cache-and-network',
    context: useMemo(
      () => ({
        suspense: true,
      }),
      []
    ),
  })
  useQuery({
    query: GetAnalyticsMilestones,
    variables: {
      exerciseId,
    },
    requestPolicy: 'cache-and-network',
    context: useMemo(
      () => ({
        suspense: true,
      }),
      []
    ),
  })

  useEffect(() => {
    if (!exerciseId) {
      return
    }
    client.query(GetTools, {
      exerciseId,
    })

    const { unsubscribe: unsubLog } = client
      .subscription(exerciseActionLogs, {
        exerciseId,
      })
      .subscribe(({ data }) => {
        console.info('actionLog: ', data)
        // in contrast with trainee, instructor view received event for any type of actionlog, created, modified and even deleted one, please mind that when something goes awry with actionlogs
        if (data?.analyticsActionLogsSubscription?.actionLog)
          window.dispatchEvent(
            new CustomEvent<ActionLogPayload>('actionLogEvent', {
              detail: {
                actionLog: data?.analyticsActionLogsSubscription?.actionLog,
              },
            })
          )
      })

    const { unsubscribe: unsubMil } = client
      .subscription(exerciseMilestones, {
        exerciseId,
      })
      .subscribe(({ data }) => {
        console.info('milestone: ', data)
      })

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

  useGenericActionLogEvent()
}

export default useActionLogSubscriptionInstructor
