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

import isNull from 'lodash/isNull'

import { MDASH } from 'config'

import { useAuthStore } from 'features/AuthStore'
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 { BrazilPayment } from '../BrazilPayment'

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 [isOpenBrasilian, setIsOpenBrasilian] = useState(false)
  const { user } = useAuthStore()

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

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

  if (!match) return null

  const isBrasil = user?.profile.country_code === 'BR'

  const onHandleClick = (e?: MouseEvent<HTMLButtonElement>) => {
    if (isBrasil) {
      setIsOpenBrasilian(true)
    } else {
      onBuyClick(e)
    }
  }

  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 />
        {isBrasil ? null : <SelectedCard />}
      </Body>
      <Footer>
        {loader ? (
          <ArrowLoader width='204px' disabled />
        ) : (
          <Button
            disabled={!selectedPackage}
            onClick={onHandleClick}
          >
            <T9n t='buy_subscription' />
          </Button>
        )}
      </Footer>
      {selectedPackage && isOpenBrasilian && (
        <BrazilPayment
          match={match}
          open={isOpenBrasilian}
          selectedPackage={selectedPackage}
          setIsOpenBrasilian={setIsOpenBrasilian}
        />
      )}
    </Wrapper>
  )
}
