import { useEffect, useRef } from 'react'
import { useAnalytics } from '@segment/analytics-react'
import { useSelector } from 'react-redux'
import { useLocation } from 'react-router'

import { selectDiagnostics } from '~/src/store/selectors/selectDiagnostics'
import { selectEventList } from '~/src/store/selectors/selectEventList'
import { selectEventsFilter } from '~/src/store/selectors/selectEventsFilter'
import { selectUIState } from '~/src/store/selectors/selectUIState'
import { Diagnostics } from '~/src/types/diagnostics'


export const Telemetry = () => {
  const { page, track, addSourceMiddleware } = useAnalytics()
  const { pathname } = useLocation()
  const { selectedEventRecordId } = useSelector(selectUIState)
  const eventList = useSelector(selectEventList)
  const eventsFilter = useSelector(selectEventsFilter)
  const diagnostics = useSelector(selectDiagnostics)
  const debuggeeMetadata = useRef<Pick<Diagnostics, 'writeKey' | 'hostname'>>()

  useEffect(() => {
    debuggeeMetadata.current = {
      writeKey: diagnostics?.writeKey,
      hostname: diagnostics?.hostname
    }
  }, [diagnostics])

  useEffect(() => {
    addSourceMiddleware(({ payload, next }) => {
      Object.assign(payload.obj.properties, {
        debuggee: debuggeeMetadata.current
      })
      next(payload)
    })
  }, [])

  // -------- EVENT WIRINGS MUST BE AFTER SETUP HOOKS -------- \\

  useEffect(() => {
    page(undefined, pathname, { path: pathname, url: pathname })
  }, [pathname])

  useEffect(() => {
    if (eventList.length > 0) {
      track('Event List Populated')
    }
  }, [eventList.length > 0])

  useEffect(() => {
    if (eventsFilter.query.length > 0) {
      track('Query Filter Set')
    }
  }, [eventsFilter.query.length > 0])

  useEffect(() => {
    if (eventsFilter.eventTypes.length > 0) {
      track('Event Type Filter Set')
    }
  }, [eventsFilter.eventTypes.length > 0])

  useEffect(() => {
    if (selectedEventRecordId) {
      track('Event Details Viewed')
    }
  }, [selectedEventRecordId])

  return null
}
