import { useEffect } from 'react'

import map from 'lodash/map'
import isNull from 'lodash/isNull'

import { AddCardForm } from 'features/AddCardForm'
import { useCardsStore } from 'features/CardsStore'
import {
  CloseButton,
  HeaderActions,
} from 'features/PopupComponents'
import { SolidButton } from 'features/UserAccount/styled'
import { T9n } from 'features/T9n'

import { BankCard } from '../BankCard'
import {
  FormWrapper,
  Wrapper,
  Modal,
  Header,
  ModalBody,
  PaymentInfoText,
  InfoText,
} from './styled'

export const PageBankCards = () => {
  const {
    cards,
    defaultCard,
    fetchCards,
    infoModalOpen,
    isFetching,
    onDeleteCard,
    onSetDefaultCard,
    toggleInfoModal,
  } = useCardsStore()

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

  return (
    <Wrapper>
      {map(cards, (card) => (
        <BankCard
          key={card.id}
          card={card}
          checked={card.id === defaultCard?.id}
          onChange={onSetDefaultCard}
          onDelete={onDeleteCard}
          loader={isFetching}
        />
      ))}
      <PaymentInfoText>
        <T9n t='payment_info' />
      </PaymentInfoText>
      <FormWrapper>
        <AddCardForm />
      </FormWrapper>

      <Modal isOpen={infoModalOpen} withCloseButton={false}>
        <Header>
          <HeaderActions position='right'>
            <CloseButton onClick={toggleInfoModal} />
          </HeaderActions>
        </Header>
        <ModalBody>
          <InfoText>
            <T9n t='subs_will_not_be_renewed' />
          </InfoText>

          <SolidButton onClick={toggleInfoModal}>Ok</SolidButton>
        </ModalBody>
      </Modal>
    </Wrapper>
  )
}
