import { Fragment } from 'react'

import { T9n } from 'features/T9n'
import { ArrowLoader } from 'features/ArrowLoader'

import { client } from 'features/AuthServiceApp/config/clients'
import { useRecovery } from './hooks'

import {
  Modal,
  Wrapper,
  Header,
  HeaderTitle,
  Footer,
  ApplyButton,
  Text,
  Body,
} from './styled'

import { Input } from '../../../../components/Input'
import { InputGroup, Error } from '../../styled'

type Props = {
  isModalOpen: boolean,
  setIsModalOpen: (value: boolean) => void,
}

export const RecoveryPopup = (props: Props) => {
  const { isModalOpen, setIsModalOpen } = props

  const {
    closePopup,
    error,
    handleSubmit,
    isFetching,
    isSendBtnDisabled,
    isSendMessage,
    onEmailChange,
  } = useRecovery(setIsModalOpen)

  return (
    <Modal
      isOpen={isModalOpen}
      withCloseButton
      close={closePopup}
    >
      <Wrapper>
        <Header>
          <HeaderTitle>
            <T9n t='recovery_email' />
          </HeaderTitle>
        </Header>
        <Body>
          {isSendMessage ? (
            <Text>
              <T9n t='send_new_email_for_change_pass' />
            </Text>
          ) : (
            <Fragment>
              <InputGroup>
                <Input
                  autoFocus
                  type='email'
                  name='email'
                  autoComplete='email'
                  placeholderLexic='registration_email'
                  onChange={onEmailChange}
                />
              </InputGroup>
              <Error>
                <T9n t={error} />
              </Error>
            </Fragment>
          )}
          <Footer>
            {!isSendMessage ? (
              <ApplyButton onClick={handleSubmit} disabled={isSendBtnDisabled}>
                {isFetching
                  ? <ArrowLoader color={client.styles.popupLoader} />
                  : <T9n t='send' />}
              </ApplyButton>
            ) : (
              <ApplyButton onClick={closePopup}>
                Ok
              </ApplyButton>
            )}
          </Footer>
        </Body>
      </Wrapper>
    </Modal>
  )
}
