import { useCallback } from 'react'

import map from 'lodash/map'

import { MDASH } from 'config'

import { isSubscribePopup } from 'helpers'

import { Name as Names } from 'features/Name'
import { T9n } from 'features/T9n'
import { useBuyMatchPopupStore } from 'features/BuyMatchPopup/store'
import { CloseButton, HeaderActions } from 'features/PopupComponents'
import {
  Body,
  Button,
  Footer,
  Header,
  HeaderTitle,
  Wrapper,
} from 'features/BuyMatchPopup/styled'

import { MatchPackage, SubscriptionType } from '../../types'

import {
  Description,
  InfoWrapper,
  Name,
  Pass,
} from '../PackagesList/styled'

import {
  Price,
  ChooseSub,
  ChooseSubItem,
  ChooseSubList,
} from './styled'

export const SelectSubscriptionStep = () => {
  const {
    close,
    match,
    matchSubscriptions,
    onNext,
    onSubscriptionSelect,
    selectedSubscription,
  } = useBuyMatchPopupStore()

  const getPackagesCurrency = useCallback(
    (packages: Record<SubscriptionType, Array<MatchPackage>>) => {
      const packageWithValue = Object.entries(packages).find(([key, value]) => value.length)?.[1][0]
      return packageWithValue ? packageWithValue.currency : 'RUB'
    }, [],
  )

  if (!match || !matchSubscriptions) return null

  return (
    <Wrapper>
      <Header>
        {!isSubscribePopup()
        && (
          <HeaderTitle>
            <Names nameObj={match.team1} />
            {` ${MDASH} `}
            <Names nameObj={match.team2} />
            <ChooseSub>
              <T9n t='choose_subscription' />
            </ChooseSub>
          </HeaderTitle>
        )}
        <HeaderActions position='right'>
          <CloseButton onClick={close} />
        </HeaderActions>
      </Header>
      <Body marginTop={15}>
        <ChooseSubList>
          {map(matchSubscriptions, (subscription) => (
            <ChooseSubItem
              key={subscription.id}
              onClick={() => onSubscriptionSelect(subscription)}
              active={subscription === selectedSubscription}
            >
              <InfoWrapper>
                <Pass>
                  <T9n t={subscription.lexic} />
                </Pass>
                <Name>
                  <T9n t={subscription.lexic2} />
                </Name>
                <Description>
                  <T9n t={subscription.lexic3} />
                </Description>
              </InfoWrapper>

              <Price
                amount={subscription.min_price || 0}
                currency={getPackagesCurrency(subscription.packages)}
                isFrom={Boolean(subscription.min_price)}
              />
            </ChooseSubItem>
          ))}
        </ChooseSubList>
      </Body>
      <Footer>
        <Button
          disabled={!selectedSubscription}
          onClick={onNext}
        >
          <T9n t='next_choose' />
        </Button>
      </Footer>
    </Wrapper>
  )
}
