import type { ResultOf, VariablesOf } from 'gql.tada'
import { useEffect, useMemo } from 'react'
import { useQuery } from 'urql'
import { GetAnalyticsEmailThreads, GetAnalyticsMilestones } from '../../queries'
import {
  exerciseActionLogs,
  exerciseKVSubscription,
  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
    }

    const { unsubscribe: unsubLog } = client
      .subscription<ResultOf<typeof exerciseActionLogs>>(exerciseActionLogs, {
        exerciseId,
      })
      .subscribe(({ data }) => {
        if (data?.analyticsActionLogsSubscription?.actionLog) {
          window.dispatchEvent(
            new CustomEvent<ActionLogPayload>('actionLogEvent', {
              detail: {
                actionLog: data.analyticsActionLogsSubscription.actionLog,
                eventType: data.analyticsActionLogsSubscription.eventType,
              },
            })
          )
        }
      })

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

    const { unsubscribe: unsubKV } = client
      .subscription<
        ResultOf<typeof exerciseKVSubscription>,
        VariablesOf<typeof exerciseKVSubscription>
      >(exerciseKVSubscription, {
        exerciseId,
      })
      .subscribe(({ data }) => {
        // TODO: handle clear event
        console.info('kv:', data)
      })

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

  useGenericActionLogEvent()
}

export default useActionLogSubscriptionInstructor
