import { Fragment, useEffect } from 'react'

import isNull from 'lodash/isNull'

import { MDASH } from 'config'

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 { useBuyMatchPopupStore } from '../../store'
import { SelectedCard } from '../SelectedCard'
import { Subscriptions } from '../Subscriptions'
import {
  Wrapper,
  Body,
  Footer,
  Button,
  ButtonPrevious,
  Header,
  HeaderTitle,
} from '../../styled'

export const SubscriptionSelectionStep = () => {
  const {
    cards,
    fetchCards,
  } = useCardsStore()

  const {
    close,
    getSub,
    loader,
    match,
    onBuyClick,
    selectedSubName,
    selectedSubscription,
    selectedSubStep,
  } = useBuyMatchPopupStore()

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

  if (!match) return null

  return (
    <Wrapper>
      <Header>
        {selectedSubStep && (
          <HeaderActions position='left'>
            <ButtonPrevious
              onClick={getSub}
              direction='left'
            />
          </HeaderActions>
        )}
        <HeaderTitle>
          {selectedSubStep
            ? <T9n t={selectedSubName} />
            : (
              <Fragment>
                <Name nameObj={match.team1} />
                {` ${MDASH} `}
                <Name nameObj={match.team2} />
              </Fragment>
            )}
        </HeaderTitle>
        <HeaderActions position='right'>
          <CloseButton onClick={close} />
        </HeaderActions>
      </Header>
      <Body marginTop={20}>
        <Subscriptions />
        <SelectedCard />
      </Body>
      <Footer>
        {loader
          ? <ArrowLoader width='204px' disabled />
          : (
            <Button
              disabled={!selectedSubscription}
              onClick={onBuyClick}
            >
              <T9n t='buy_subscription' />
            </Button>
          )}
      </Footer>
    </Wrapper>
  )
}
