import { useEventListener } from 'ahooks'
import type { FragmentOf } from 'gql.tada'
import { matchPath } from 'react-router-dom'
import { useClient } from 'urql'
import { graphql } from '../../graphql'
import {
  SetEmailThreadArchive,
  setIsUnreadChannel,
  setIsUnreadEmailThread,
} from '../../mutations.client'

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const ActionLogLookup = graphql(`
  fragment _ on ActionLogType @_unmask {
    channel {
      id
    }
    team {
      id
    }
    details {
      __typename
    }
    type
  }
`)

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const LogTypeFrag = graphql(`
  fragment _ on ActionLogType @_unmask {
    type
  }
`)

// TODO: make it resilient towards multiple exerciseIds
export const isInCurrentContext = (
  actionLog: FragmentOf<typeof ActionLogLookup>
): boolean => {
  const match = matchPath(
    {
      path: '/:context/:exerciseId/:teamId/:channelId/:loc',
      end: false,
    },
    window.location.pathname
  )
  switch (match?.params.context) {
    case 'instructor':
    case 'trainee':
      break
    default:
      return false
  }
  switch (actionLog.type) {
    case 'EMAIL':
      return (
        match.params.teamId === actionLog.team.id &&
        match.params.loc === 'email'
      )
    case 'FORM':
      return (
        match.params.teamId === actionLog.team.id && match.params.loc === 'form'
      )
    case 'INJECT':
    case 'CUSTOM_INJECT':
      return (
        match.params.teamId === actionLog.team.id &&
        match.params.loc === 'info' &&
        match.params.channelId === actionLog.channel.id
      )
    case 'TOOL':
      return (
        match.params.teamId === actionLog.team.id && match.params.loc === 'tool'
      )
    default:
      return false
  }
}
export const getNotificationMessage = (
  type: FragmentOf<typeof LogTypeFrag>['type']
): string => {
  switch (type) {
    case 'EMAIL':
      return 'New email'
    case 'FORM':
      return 'New questionnaire'
    case 'INJECT':
    // fallthrough
    case 'CUSTOM_INJECT':
      return 'New inject'
    case 'TOOL':
      return 'New tool response'
    default:
      throw new Error(`Unknown log type: ${type}`)
  }
}

export const useGenericActionLogEvent = () => {
  const client = useClient()
  useEventListener('actionLogEvent', e => {
    const newActionLog = e.detail.actionLog

    if (!isInCurrentContext(newActionLog)) {
      client
        .mutation(setIsUnreadChannel, {
          channelId: newActionLog.channel.id,
          teamId: newActionLog.team.id,
          isUnread: true,
        })
        .toPromise()
    }
    if (
      newActionLog.type === 'EMAIL' &&
      newActionLog.details.__typename === 'EmailType'
    ) {
      client
        .mutation(setIsUnreadEmailThread, {
          threadId: newActionLog.details.thread.id,
          isUnread: true,
          teamId: newActionLog.team.id,
        })
        .toPromise()
      if (newActionLog.details.thread.archived) {
        client
          .mutation(SetEmailThreadArchive, {
            emailThreadId: newActionLog.details.thread.id,
            state: false,
          })
          .toPromise()
      }
    }
  })
}
