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

import isNull from 'lodash/isNull'

import { MDASH } from 'config'
import { payments } from 'config/payments'
import { client } from 'config/clients'

import { CountryCodeType, getCountryCode } from 'requests/getCountryCode'

import { CloseButton, HeaderActions } from 'features/PopupComponents'
import { T9n } from 'features/T9n'
import { Name } from 'features/Name'
import { useCardsStore } from 'features/CardsStore'
import { ArrowLoader } from 'features/ArrowLoader'
import { Arrow } from 'features/HeaderFilters/components/DateFilter/styled'
import { useAuthStore } from 'features/AuthStore'

import { IframePayment } from '../IframePayment'

import { useBuyMatchPopupStore } from '../../store'
import { SelectedCard } from '../SelectedCard'
import { Packages } from '../Packages'
import {
  Wrapper,
  Body,
  Footer,
  Button,
  ButtonPrevious,
  Header,
  HeaderTitle,
} from '../../styled'

export const PackageSelectionStep = () => {
  const {
    cards,
    fetchCards,
  } = useCardsStore()
  const [isOpenIframe, setIsOpenIframe] = useState(false)
  const [countryCode, setCountryCode] = useState<CountryCodeType | null>(null)
  const {
    logout,
    setSearch,
    user,
  } = useAuthStore()

  const {
    close,
    disabledBuyBtn,
    goBack,
    hasPreviousStep,
    lastSelectedPackage,
    loader,
    match,
    onBuyClick,
    selectedPackage,
    selectedSubscription,
    setDisabledBuyBtn,
    setLastSelectedPackage,
  } = useBuyMatchPopupStore()

  useEffect(() => {
    getUserCountry()
    if (isNull(cards)) {
      fetchCards()
    }
  }, [cards, fetchCards])

  const paymentSystem = useMemo(() => {
    switch (countryCode?.country_code) {
      case 'BR':
        return payments.brasil
      case 'TN':
        return payments.tunisia
      default:
        return payments[client.name]
    }
  }, [countryCode])

  const isIframePayment = useMemo(() => {
    switch (countryCode?.country_code) {
      case 'BR':
      case 'TN':
        return true
      default:
        return false
    }
  }, [countryCode])

  if (!match) return null

  const getUserCountry = () => {
    getCountryCode().then(setCountryCode)
  }

  const onHandleClick = (e?: MouseEvent<HTMLButtonElement>) => {
    cards?.length
      && lastSelectedPackage === selectedPackage?.id
      && setDisabledBuyBtn(true)
    if (isIframePayment) {
      setIsOpenIframe(true)
    } else {
      onBuyClick(e)
    }
    setLastSelectedPackage(selectedPackage?.id || '')
  }

  return (
    <Wrapper>

      <Header>
        {hasPreviousStep && (
          <HeaderActions position='left'>
            <ButtonPrevious onClick={goBack}>
              <Arrow direction='left' />
            </ButtonPrevious>
          </HeaderActions>
        )}
        <HeaderTitle>
          {hasPreviousStep && selectedSubscription ? (
            <T9n t={selectedSubscription?.lexic} />
          ) : (
            <Fragment>
              <Name nameObj={match.team1} />
              {` ${MDASH} `}
              <Name nameObj={match.team2} />
            </Fragment>
          )}
        </HeaderTitle>
        <HeaderActions position='right'>
          <CloseButton onClick={close} />
        </HeaderActions>
      </Header>
      <Body marginTop={20}>
        <Packages />
        {!isIframePayment && <SelectedCard />}
      </Body>
      <Footer>
        {loader ? (
          <ArrowLoader width='204px' disabled />
        ) : (
          <Button
            disabled={!selectedPackage || disabledBuyBtn}
            onClick={(e) => {
              if (user) {
                onHandleClick(e)
              } else {
                setSearch(window.location.search)
                logout('saveToken')
              }
            }}
          >
            <T9n t='buy_subscription' />
          </Button>
        )}
      </Footer>
      {selectedPackage && isIframePayment && (
        <IframePayment
          match={match}
          open={isOpenIframe}
          paymentSystem={paymentSystem}
          selectedPackage={selectedPackage}
          setIsOpenIframe={setIsOpenIframe}
        />
      )}
    </Wrapper>
  )
}
