import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { toast } from 'react-toastify';
import { Button, Form, FormGroup, Input } from 'reactstrap';
import withRedirect from '../../hoc/withRedirect';
import { requstResetForgotPassword } from '../../helpers/rest';
import { useTranslation } from 'react-i18next';

const ForgetPasswordForm = ({ setRedirect, setRedirectUrl, layout }) => {
  // State
  const [email, setEmail] = useState('');
  const [submitting, setSubmitting] = useState(false);

  const { t } = useTranslation('auth');

  // Handler
  const handleSubmit = e => {
    e.preventDefault();
    setSubmitting(true);
    if (email) {
      requstResetForgotPassword(email)
        .then(() => {
          toast.success(`An email is sent to ${email} with password reset link`);
          setRedirect(true);
        })
        .catch(error => {})
        .finally(() => {
          setSubmitting(false);
        });
    }
  };

  useEffect(() => {
    setRedirectUrl(`/auth/confirm-mail?email=${email}`);
  }, [setRedirectUrl, layout, email]);

  return (
    <Form className="mt-4" onSubmit={handleSubmit}>
      <FormGroup>
        <Input
          className="form-control"
          placeholder={t('forgotForm.email')}
          value={email}
          onChange={({ target }) => setEmail(target.value)}
          type="email"
          required
          disabled={submitting}
          data-testid="email"
        />
      </FormGroup>
      <FormGroup>
        <Button color="primary" block disabled={!email || submitting} data-testid="submit">
          {submitting ? t('forgotForm.submitting') : t('forgotForm.submit')}
        </Button>
      </FormGroup>
      {/* <Link className="fs--1 text-600" to="#!">
        I can't recover my account using this page
        <span className="d-inline-block ml-1">&rarr;</span>
      </Link> */}
    </Form>
  );
};

ForgetPasswordForm.propTypes = {
  setRedirect: PropTypes.func.isRequired,
  setRedirectUrl: PropTypes.func.isRequired,
  layout: PropTypes.string
};

ForgetPasswordForm.defaultProps = { layout: 'basic' };

export default withRedirect(ForgetPasswordForm);
