import { css } from '@emotion/css'
import type { FC, ReactNode } from 'react'
import { useMemo } from 'react'
import { createPortal } from 'react-dom'
import { useSubscriptionContext } from '../../context/SubscriptionContext'
import type { ActionLog } from '../../fragments/ActionLog.generated'
import EmailService from './actionLogComponents/EmailService'
import SubscriptionService from './actionLogComponents/SubscriptionService'
import TeamMilestonesService from './actionLogComponents/TeamMilestonesService'

const portalElement = css`
  display: none;
`

interface ManagerProps {
  getPopup?: (actionLog: ActionLog) => ReactNode
  teamId?: string
  selectedThreadId?: string
}

// TODO: refactor this hacky code - it could be a custom hook instead (check for issues with cache synchronization)

/**
 * Renders the subscription service components in a hidden portal:
 * necessary for the subscriptions to work in the trainee/instructor views.
 */
const Manager: FC<ManagerProps> = ({ getPopup, teamId, selectedThreadId }) => {
  const { teamIds, instructorContext } = useSubscriptionContext()
  const subscribed = useMemo(
    () =>
      teamIds.map(id => (
        <div key={id}>
          <SubscriptionService
            teamId={id}
            showNotifications={instructorContext && teamId !== id}
            getPopup={getPopup}
          />
          <EmailService teamId={id} selectedThreadId={selectedThreadId} />
          {instructorContext && <TeamMilestonesService teamId={id} />}
        </div>
      )),
    [teamIds, instructorContext, teamId, getPopup, selectedThreadId]
  )

  return (
    <>
      {createPortal(
        <div className={portalElement}>{subscribed}</div>,
        document.getElementById('connection')!
      )}
    </>
  )
}

export default Manager
