import { useMemo } from 'react'

import map from 'lodash/map'
import size from 'lodash/size'
import styled, { css } from 'styled-components/macro'

import { isMobileDevice } from 'config/userAgent'

import type { MatchSubscription, SubscriptionType } from 'features/BuyMatchPopup/types'
import { T9n } from 'features/T9n'

import { getCorrectPaymentTabs } from './helpers'

type ListProps = {
  countSubscriptions: number,
}
const List = styled.ul<ListProps>`
  display: flex;
  min-width: 395px;
  justify-content: ${({ countSubscriptions }) => (countSubscriptions === 1
    ? 'center'
    : 'space-between')};
  ${isMobileDevice
    ? css`
      min-width: 90%;
      width: 90%;
      position: relative;
      justify-content: center;
      @media screen and (orientation: landscape){
        margin-top: -5px;
        width: 50%;
        min-width: 50%;
      }
    `
    : ''};
`

type ItemProps = {
  active?: boolean,
}

const Item = styled.li<ItemProps>`
  position: relative;
  font-weight: 600;
  font-size: 16px;
  line-height: 47px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: rgba(255, 255, 255, 0.5);
  cursor: pointer;
  transition: color 0.3s;

  ::after {
    transition: background-color 0.3s;
    position: absolute;
    content: '';
    bottom: 0px;
    width: 130px;
    height: 3px;
  }

  ${({ active }) => (
    active
      ? css`
        color: #fff;
        ::after {
          background-color: #fff;
        }
      `
      : ''
  )}
    ${isMobileDevice
    ? css`
     font-size: 10px;
     width: 33%;
     white-space: nowrap;
     ::after {
       height: 2px;
     }
    `
    : ''};
`

type Props = {
  className?: string,
  onPeriodSelect: (period: SubscriptionType) => void,
  selectedPeriod: SubscriptionType,
  selectedSubscription: MatchSubscription,
}

export const PaymentPeriodTabs = ({
  className,
  onPeriodSelect,
  selectedPeriod,
  selectedSubscription,
}: Props) => {
  const matchSubscriptionsWithValues = useMemo(() => (
    getCorrectPaymentTabs(selectedSubscription)
  ), [selectedSubscription])

  return (
    <List className={className} countSubscriptions={size(matchSubscriptionsWithValues)}>
      {map(matchSubscriptionsWithValues, ({ tabLexic, type }) => (
        <Item
          key={type}
          active={selectedPeriod === type}
          onClick={() => onPeriodSelect(type)}
        >
          <T9n t={tabLexic} />
        </Item>
      ))}
    </List>
  )
}
