import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { Link, useHistory, useLocation } from 'react-router-dom';
import { toast } from 'react-toastify';
import { Button, Form, Row, Col, FormGroup, Input, CustomInput, Label } from 'reactstrap';
import Divider from '../common/Divider';
import SocialAuthButtons from './SocialAuthButtons';
import withRedirect from '../../hoc/withRedirect';
import { useAuth } from '../../context/UserAuth';
//import { signin } from '../../services/authService';
import { useTranslation } from 'react-i18next';

const LoginForm = ({ setRedirect, hasLabel, layout }) => {
  // State
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [remember, setRemember] = useState(true);
  const [isDisabled, setIsDisabled] = useState(true);

  const history = useHistory();

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

  // We want to redirect to /profile after logging in , because we need to reserve `/` to be our 'mrketing site'
  // So if somehow location.state says "/" , then we want to redirect to /profile
  const defaultLocation = { pathname: "/profile" };
  let { from } = location.state || { from: defaultLocation };

  const { login, setCurrentUser } = useAuth();

  // Handler
  const handleSubmit = async e => {
    e.preventDefault();
    const credentials = {email, password}
    setIsDisabled(true);
    const user = await login(credentials)
    if(user){
      setCurrentUser(user)
      //localStorage.setItem('user', user)
      toast.success(`Signed in as ${email}`);
      setEmail('')
      setPassword('')
      //setRedirect(true)
      const finalDestination = from.pathname == "/" ? defaultLocation : from
      history.replace(finalDestination);
    }else{
      toast.error("Incorrect email or password");
    }
    setIsDisabled(false);
  };

  useEffect(() => {
    setIsDisabled(!email || !password);
  }, [email, password]);

  return (
    <Form onSubmit={handleSubmit}>
      <FormGroup>
        {hasLabel && <Label>{ t('signinForm.email')}</Label>}
        <Input
          data-testid="email"
          placeholder={!hasLabel ? t('signinForm.email') : ''}
          value={email}
          onChange={({ target }) => setEmail(target.value)}
          type="email"
        />
      </FormGroup>
      <FormGroup>
        {hasLabel && <Label>{t('signinForm.password')}</Label>}
        <Input
          data-testid="password"
          placeholder={!hasLabel ? t('signinForm.password') : ''}
          value={password}
          onChange={({ target }) => setPassword(target.value)}
          type="password"
        />
      </FormGroup>
      <Row className="justify-content-between align-items-center">
        <Col xs="auto">
          <CustomInput
            id="customCheckRemember"
            label={ t('signinForm.remember') }
            checked={remember}
            onChange={({ target }) => setRemember(target.checked)}
            type="checkbox"
          />
        </Col>
        <Col xs="auto">
          <Link className="fs--1" to={`/auth/forget-password`}>
            Forget Password?
          </Link>
          {/* <a href="https://www.jamkazam.com/request_reset_password" target='_blank'>Forgot Password</a> */}
        </Col>
      </Row>
      <FormGroup>
        <Button color="primary" block className="mt-3" data-testid="submit" disabled={isDisabled}>
          { t('signinForm.submit') }
        </Button>
      </FormGroup>
      {/* <Divider className="mt-4">or log in with</Divider>
      <SocialAuthButtons /> */}
    </Form>
  );
};

LoginForm.propTypes = {
  setRedirect: PropTypes.func.isRequired,
  layout: PropTypes.string,
  hasLabel: PropTypes.bool
};

LoginForm.defaultProps = {
  layout: 'basic',
  hasLabel: false
};

export default withRedirect(LoginForm);
