import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { useHistory } from 'react-router-dom';
import { toast } from 'react-toastify';
import { Button, Form, FormGroup, Input, InputGroup, Label } from 'reactstrap';
import withRedirect from '../../hoc/withRedirect';
import { useAuth } from '../../context/UserAuth';
import { useTranslation } from 'react-i18next';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import ReCAPTCHA from "react-google-recaptcha";
import useRecaptcha from '../../hooks/useRecaptcha';
import useJamTrackShopping from '../../hooks/useJamTrackShopping';

const JKRegistrationForm = ({ hasLabel, jamTrack, jamTrackArtistName }) => {
  // State
  const [firstName, setFirstName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [isDisabled, setIsDisabled] = useState(true);
  const [showPassword, setShowPassword] = useState(false);
  
  const { capchaToken, recaptchaRef, handleRecaptcha } = useRecaptcha();

  const { addToCart } = useJamTrackShopping();

  // Context
  const { signUp, setCurrentUser, currentUser } = useAuth();

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

  const history = useHistory();

  // Handler
  const handleSubmit = async e => {
    e.preventDefault();
    setIsDisabled(true);

    try {
      const params = {
        first_name: firstName,
        email,
        password,
        password_confirmation: password,
        terms: true
      };
      const response = await signUp(params);
      const user = await response.json();
      setCurrentUser(user);
      toast.success(`${t('signupForm.successMessage')} ${firstName}`);
    } catch (error) {
      console.error(error);
      toast.error(`Registration failed. Please try again.`);
      setIsDisabled(false);
    }
   
  };

  useEffect(() => {
    const addJamTrackToCart = async () => {
      try{
        await addToCart(jamTrack);
      }catch(error){
        console.error(error);
      }
    }

    if (currentUser) {
      if(jamTrack){
        addJamTrackToCart();
      }else if(jamTrackArtistName){
        history.push(`/jamtracks?artist=${jamTrackArtistName}`);
      }else{
        history.push('/public/downloads');
      }
    }
  }, [currentUser, jamTrack, jamTrackArtistName]);

  useEffect(() => {
    setIsDisabled(!firstName || !email || !password || (process.env.REACT_APP_RECAPTCHA_ENABLED === 'true' && !capchaToken));
  }, [firstName, email, password, capchaToken]);

  // useEffect(() => {
  //   if (process.env.REACT_APP_RECAPTCHA_ENABLED === 'true') {
  //     setIsDisabled(!(capchaToken.length > 0));
  //   }
  // }, [capchaToken]);

  return (
    <Form onSubmit={handleSubmit}>
      <FormGroup>
        {hasLabel && <Label>{t('signupForm.firstName')}</Label>}
        <Input placeholder={!hasLabel ? t('signupForm.firstName') : ''} value={firstName} onChange={({ target }) => setFirstName(target.value)} />
      </FormGroup>
      <FormGroup>
        {hasLabel && <Label>{t('signupForm.email')}</Label>}
        <Input
          placeholder={!hasLabel ? t('signupForm.email') : ''}
          value={email}
          onChange={({ target }) => setEmail(target.value)}
          type="email"
        />
      </FormGroup>
      {/* <div className="form-row"> */}
      <FormGroup>
        {hasLabel && <Label>{t('signupForm.password')}</Label>}
        <InputGroup>
          <Input
            placeholder={!hasLabel ? t('signupForm.password') : ''}
            value={password}
            onChange={({ target }) => setPassword(target.value)}
            type={showPassword ? 'text' : 'password'}
          />
          <div className="input-group-append">
            <span className="input-group-text">
              <a href="#" onClick={e => {
                e.preventDefault();
                setShowPassword(!showPassword);
              }}>
                {showPassword ? (
                  <FontAwesomeIcon icon="eye-slash" onClick={() => setShowPassword(false)} />
                ) : (
                  <FontAwesomeIcon icon="eye" onClick={() => setShowPassword(true)} />
                )}
              </a>
            </span>
          </div>
        </InputGroup>
        <div className='mt-2'>{t('signupForm.passwordRequirements')}</div>
      </FormGroup>

      {process.env.REACT_APP_RECAPTCHA_ENABLED === 'true' && (
        <FormGroup>
          <ReCAPTCHA 
            sitekey={process.env.REACT_APP_SITE_KEY} 
            ref={recaptchaRef} 
            onChange={handleRecaptcha}
          />
        </FormGroup>
      )}

      <FormGroup>
        <Button color="primary" block className="mt-3" disabled={isDisabled}>
        {t('signup')}
        </Button>
      </FormGroup>

    </Form>
  );
};

JKRegistrationForm.propTypes = {
  hasLabel: PropTypes.bool,
  jamTrack: PropTypes.object,
  jamTrackArtistName: PropTypes.string
};

JKRegistrationForm.defaultProps = {
  hasLabel: false
};

export default withRedirect(JKRegistrationForm);
