import { useState } from 'react'

import isEmpty from 'lodash/isEmpty'

import { AddCardFormInner } from 'features/AddCardForm/components/Form'
import { useCardsStore } from 'features/CardsStore'
import { useBuyMatchPopupStore } from 'features/BuyMatchPopup/store'
import {
  CloseButton,
  HeaderActions,
} from 'features/PopupComponents'
import { T9n } from 'features/T9n'
import { Arrow } from 'features/HeaderFilters/components/DateFilter/styled'

import { CardsList } from '../CardsList'

import {
  Wrapper,
  Body,
  Header,
  HeaderTitle,
  Button,
  ButtonBlock,
  ButtonClear,
  ButtonPrevious,
} from '../../styled'

type CardStepType = {
  btnName?: string,
  closeHandle?: () => void,
  title?: string,
}

export const CardStep = ({
  btnName,
  closeHandle,
  title,
}: CardStepType) => {
  const [clearInputs, setClearInputs] = useState(false)
  const { cards, isHighlightsPage } = useCardsStore()
  const {
    close,
    goBack,
    showClearBtn,
  } = useBuyMatchPopupStore()

  const emptyCards = isEmpty(cards)

  return (
    <Wrapper width={642}>
      <Header>
        <ButtonPrevious onClick={goBack}>
          {isHighlightsPage ? '' : <Arrow direction='left' />}
        </ButtonPrevious>
        <HeaderTitle>
          <T9n t={title ?? 'pay'} />
        </HeaderTitle>
        <HeaderActions position='right'>
          <CloseButton onClick={isHighlightsPage && closeHandle ? closeHandle : close} />
        </HeaderActions>
      </Header>
      <Body padding='12px 40px 0 40px'>
        <CardsList />
        <AddCardFormInner
          onAddSuccess={goBack}
          initialformOpen={emptyCards}
          inputsBackground='rgba(255, 255, 255, 0.1)'
          clearInputs={clearInputs}
          setClearInputs={setClearInputs}
        >
          <ButtonBlock showClearBtn={showClearBtn}>
            {isHighlightsPage
            && showClearBtn && (
              <ButtonClear onClick={(e) => {
                e.preventDefault()
                setClearInputs(true)
              }}
              >
                <T9n t='clear' />
              </ButtonClear>
            )}
            <Button type='submit'>
              <T9n t={btnName ?? 'add'} />
            </Button>
          </ButtonBlock>
        </AddCardFormInner>
      </Body>
    </Wrapper>
  )
}
