import React, { useEffect } from 'react'
import { useWindowSize } from '../../hooks'
import { Button, Modal } from 'antd'
import { isMobile } from 'react-device-detect'
import { useSessionFlag } from '../../hooks/useSessionFlag'
import { AuthApiSauce, Apisauce } from '../../services'
import { useAnalytics } from '../../hooks/useAnalytics'
import { SEGMENT_EVENTS } from '../../constants/segment'
import { Response } from '../../redux/Common/types'

import './SendLoginLinkEmailModal.scss'
import { useTypedSelector } from '../../redux/rootReducer'
import { selectTalentProfile, selectUserData } from '../../redux/User/selector'
import { createTemplateForIndustry } from '../../services/profile-templates/TemplateService'

function isResponseSuccess(response: Response<unknown> | null): boolean {
  if (response && 'ok' in response) {
    return !!response.ok
  }

  // GeneralApiProblem do not contain the `ok` property
  return false
}

function SendLoginLinkEmailModal() {
  const { height } = useWindowSize()
  const { sendSegmentEvent } = useAnalytics()
  const talentProfile = useTypedSelector(selectTalentProfile)
  const user = useTypedSelector(selectUserData)

  const {
    displayName,
    id: talentProfileId,
    modules,
    category
  } = talentProfile || {}
  const { id: userId } = user || {}

  useEffect(() => {
    if (!displayName || !talentProfileId || !userId) {
      return
    }

    // this means the profile has been edited, so we don't update with a template - we don't want to override changes made by the user
    const hasProfileChanges = modules?.length
    if (hasProfileChanges) {
      return
    }

    const template = createTemplateForIndustry(category?.name)

    ;(async () => {
      const response = await Apisauce.autoSaveProfile(template as any) // need to cast to `any` because `localization` is required in the type but not in the template

      if (isResponseSuccess(response)) {
        sendSegmentEvent(SEGMENT_EVENTS.POPULATE_MODULES_SUCCESS)
      } else {
        sendSegmentEvent(SEGMENT_EVENTS.POPULATE_MODULES_FAILURE)
      }
    })()
  }, [displayName, talentProfileId, userId, modules, category])

  // prevents sending login links on reload or when tab is inactive
  const [isLoginLinkEmailSent, setIsLoginLinkEmailSent] = useSessionFlag(
    'sent-login-link',
    false
  )

  useEffect(() => {
    sendSegmentEvent(SEGMENT_EVENTS.VIEW_SEND_LOGIN_EMAIL_PAGE)
  }, [])

  const sendLoginLinkEmail = async () => {
    const response = await AuthApiSauce.sendLoginLinkEmail()

    if (isResponseSuccess(response)) {
      sendSegmentEvent(SEGMENT_EVENTS.REQUEST_LOGIN_EMAIL_SUCCESS)
    } else {
      sendSegmentEvent(SEGMENT_EVENTS.REQUEST_LOGIN_EMAIL_FAILURE)
    }
  }

  useEffect(() => {
    if (!isLoginLinkEmailSent) {
      setIsLoginLinkEmailSent(true)
      sendLoginLinkEmail()
    }
  }, [isLoginLinkEmailSent])

  return (
    <Modal
      visible={true}
      closable={false}
      title="Check your inbox"
      width={664}
      mask={false}
      maskClosable={false}
      className="confirm-export-modal"
      wrapClassName="confirm-export-modal-wrapper"
      bodyStyle={{
        maxHeight: isMobile ? (height || 0) - 182 : 'unset'
      }}
      footer={null}
    >
      <p className="modal-paragraph">
        Switch to a bigger screen to access full functionality at komi.io/login
      </p>
      <Button
        type="link"
        onClick={sendLoginLinkEmail}
        className="resend-button"
      >
        Resend a login link
      </Button>
    </Modal>
  )
}

export default SendLoginLinkEmailModal
