import {
  MouseEvent,
  useCallback,
  useEffect,
  useState,
} from 'react'

import { PAGES, ProfileTypes } from 'config'
import { ClientNames } from 'config/clients/types'
import { payments, PaymentSystem } from 'config/payments'

import isNumber from 'lodash/isNumber'

import { useLexicsStore } from 'features/LexicsStore'
import { useBuyMatchPopupStore } from 'features/BuyMatchPopup/store'
import { getProfileUrl } from 'features/ProfileLink/helpers'

import { getMatchInfo } from 'requests/getMatchInfo'
import { getPaymentUrl } from 'requests/getPaymentUrl'

import { redirectToUrl } from 'helpers'

import type { Props } from './index'

type ResponsePayment = {
  url: string,
}

type ResponsePaymentArray = ResponsePayment | null

export const useIframePayment = ({
  match,
  open,
  paymentSystem,
  selectedPackage,
  setIsOpenIframe,
}: Props) => {
  const { close } = useBuyMatchPopupStore()

  const [src, setSrc] = useState('')
  const [error, setError] = useState('')
  const [isPaymentProcessing, setIsPaymentProcessing] = useState(false)
  const { translate } = useLexicsStore()

  const { id, sportType } = match

  const {
    name,
    nameLexic,
    originalObject,
    pass,
  } = selectedPackage

  const teams = isNumber(nameLexic) ? translate(String(nameLexic)) : name
  const pack = translate(String(pass))

  const matchLink = getProfileUrl({
    id,
    profileType: ProfileTypes.MATCHES,
    sportType,
  })

  const closePopup = useCallback(async (e?: MouseEvent) => {
    e?.stopPropagation()

    if (error) {
      setIsOpenIframe(false)
      setError('')
    }

    const accessMatch = await getMatchInfo(sportType, id)
    if (accessMatch?.access) {
      setIsPaymentProcessing(false)
      setIsOpenIframe(false)
      setError('')
      close()
      redirectToUrl(matchLink)
    }
  }, [close, error, id, matchLink, setIsOpenIframe, sportType])

  const paymentRequest = async () => {
    let url_cancel
    let url_return
    let action: Parameters<typeof getPaymentUrl>[0]['action']

    switch (paymentSystem) {
      case PaymentSystem.Paymee:
        url_cancel = `${window.origin}/failed-paymee`
        url_return = null
        // paymee не умеет работать с подписками
        action = 'one_payment'
        break
      default:
        url_return = `${window.location.origin}${PAGES.thanksForSubscribe}`
        action = pass === 'pass_match_access' ? 'one_payment' : 'create_subscription'
        break
    }

    const payment: ResponsePaymentArray = await getPaymentUrl({
      action,
      item: originalObject,
      product_name: `${pack} ${teams}`,
      service: paymentSystem,
      url_cancel,
      url_return,
    })
    setSrc(payment?.url || '')
  }

  if (paymentSystem === payments[ClientNames.Brasil]) {
  // eslint-disable-next-line
    window.onmessage = function (event) {
      if (event.data === 'close') {
        closePopup()
      }
    }
  }

  useEffect(() => {
    let interval: ReturnType<typeof setInterval>
    let timeout: ReturnType<typeof setTimeout>

    const paymentCallback = (event: MessageEvent<{ event_id: string }>) => {
      if (event.data.event_id === 'paymee.complete') {
        setIsPaymentProcessing(true)
        interval = setInterval(() => closePopup(), 2000)
        timeout = setTimeout(() => {
          clearInterval(interval)
          setIsPaymentProcessing(false)
          setError('failed_paymee')
          setSrc('')
        }, 60000)
      }
    }
    if (paymentSystem === payments[ClientNames.Tunisia]) {
      window.addEventListener(
        'message',
        paymentCallback,
        false,
      )
    }
    return () => {
      window.removeEventListener(
        'message',
        paymentCallback,
        false,
      )
      clearInterval(interval)
      clearTimeout(timeout)
    }
  }, [closePopup, paymentSystem])

  useEffect(() => {
    if (open) {
      (async () => {
        try {
          await paymentRequest()
        } catch (err) {
          setError('error_payment_unsuccessful')
        }
      })()
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedPackage, open])

  return {
    closePopup,
    error,
    isPaymentProcessing,
    matchLink,
    src,
  }
}
