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

import { useHistory } from 'react-router-dom'

import { ProfileTypes } from 'config'

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 { getBrazilPaymentUrl } from 'requests/getBrazilPaymentUrl'

import type { Props } from './index'

type ResponsePayment = {
  url: string,
}

type ResponsePaymentArray = ResponsePayment | null

export const useBrazilPayment = ({
  match,
  open,
  selectedPackage,
  setIsOpenBrasilian,
}: Props) => {
  const history = useHistory()
  const { close } = useBuyMatchPopupStore()

  const [src, setSrc] = useState('')
  const [error, setError] = useState('')
  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 = async (e?: MouseEvent) => {
    e?.stopPropagation()
    setIsOpenBrasilian(false)
    setError('')

    const accessMatch = await getMatchInfo(sportType, id)
    if (accessMatch?.access) {
      close()
      history.push(matchLink)
    }
  }

  // eslint-disable-next-line
   window.onmessage = function (event) {
    if (event.data === 'close') {
      closePopup()
    }
  }
  useEffect(() => {
    if (open) {
      (async () => {
        try {
          const json: ResponsePaymentArray = await getBrazilPaymentUrl({
            action: pass === 'pass_match_access' ? 'one_payment' : 'create_subscription',
            item: originalObject,
            product_name: `${pack} ${teams}`,
          })
          setSrc(json?.url || '')
        } catch (err) {
          setError('error_payment_unsuccessful')
        }
      })()
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedPackage, open])

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