import { 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,
  Header,
  HeaderTitle,
} from '../../styled'

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

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

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

  if (!match) return null

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