import {
  useEffect,
  useState,
  MouseEvent,
  useMemo,
} from 'react'
import { useHistory } from 'react-router-dom'

import isNull from 'lodash/isNull'

import {
  isMobileDevice,
  client,
  payments,
  CountryCode,
} from 'config'

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

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

import { ClientNames } from 'config/clients/types'

import { ChooseSub, Footer } from './styled'

import { IframePayment } from '../IframePayment'

import { useBuyMatchPopupStore } from '../../store'
import { SelectedCard } from '../SelectedCard'
import { Packages } from '../Packages'
import {
  Wrapper,
  Body,
  Button,
  Header,
  ButtonPrevious,
} 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,
    lastSelectedPackage,
    loader,
    match,
    matchPackages,
    onBuyClick,
    selectedPackage,
    setDisabledBuyBtn,
    setLastSelectedPackage,
  } = useBuyMatchPopupStore()

  const { defaultCard } = useCardsStore()

  const history = useHistory()

  const hasCard = Boolean(defaultCard)

  const buttonId = hasCard ? 'purchase_buy' : 'purchase_next'
  const buttonLexic = hasCard ? 'buy_subscription' : 'next_choose'

  const hasOnlyOneSubscription = matchPackages.length === 1

  const titleLexic = hasOnlyOneSubscription ? 'how_to_watch' : 'choose_subscription'

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

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

  const isIframePayment = useMemo(() => {
    switch (true) {
      case countryCode?.country_code === CountryCode.BR:
      case countryCode?.country_code === CountryCode.TN:
      case countryCode?.country_code === CountryCode.IN:
      case client.name === ClientNames.India:
        return true
      default:
        return false
    }
  }, [countryCode])

  if (!match) return null

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

  const onHandleClick = (e: MouseEvent<HTMLButtonElement>, matchPackage?: MatchPackage) => {
    if (user) {
      cards?.length
        && lastSelectedPackage === selectedPackage?.id
        && setDisabledBuyBtn(true)
      if (isIframePayment) {
        setIsOpenIframe(true)
      } else {
        onBuyClick(e, matchPackage)
      }
      setLastSelectedPackage(selectedPackage?.id || '')
    } else {
      setSearch(window.location.search)
      logout('saveToken')
    }
  }

  if (isMobileDevice) {
    const handleBackClick = () => {
      close()
      history.goBack()
    }

    return (
      <Wrapper padding='0 16px'>
        <Header>
          <ButtonPrevious aria-label='Back' onClick={handleBackClick}>
            <Arrow direction='left' />
          </ButtonPrevious>
          <ChooseSub>
            <T9n t={titleLexic} />
          </ChooseSub>
        </Header>
        <Body>
          <Packages
            onButtonClick={onHandleClick}
            buttonId={buttonId}
            buttonLexic={buttonLexic}
          />
        </Body>
      </Wrapper>
    )
  }

  return (
    <Wrapper
      width={hasOnlyOneSubscription ? 624 : undefined}
      padding={hasOnlyOneSubscription ? '60px' : '60px 80px'}
    >
      <Header>
        <ChooseSub>
          <T9n t={titleLexic} />
        </ChooseSub>
        <HeaderActions position='right'>
          <CloseButton onClick={close} />
        </HeaderActions>
      </Header>
      <Body marginTop={40}>
        <Packages />
      </Body>
      <Footer hasCard={hasCard}>
        {!isIframePayment && <SelectedCard />}
        <Button
          disabled={!selectedPackage || disabledBuyBtn}
          onClick={onHandleClick}
          id={buttonId}
        >
          {loader ? (
            <ArrowLoader disabled />
          ) : (
            <T9n t={buttonLexic} />
          )}
        </Button>
      </Footer>
      {selectedPackage && isIframePayment && (
        <IframePayment
          match={match}
          open={isOpenIframe}
          paymentSystem={paymentSystem}
          selectedPackage={selectedPackage}
          setIsOpenIframe={setIsOpenIframe}
        />
      )}
    </Wrapper>
  )
}
