import React, { useState } from 'react'
import { connect } from 'react-redux'
import { Redirect, useLocation, Link } from 'react-router-dom'
import { Formik, Form } from 'formik'
import { authenticateUserAsync, clearAuthenticationState } from '../../redux/user/user.action'
import { ATextField } from '../form-fields/form-field.component'
import ToastComponent from "../utility/toast/toast.component";
import WithSpinner from "../utility/hoc/spinner/with-spinner.component"
//images
import formHeaderImg from '../app-header/assets/logo.svg'
import illustration from './images/illustration.svg'
import middleIllustration from './images/middle-caption.svg'
import bottomIllustration from './images/bottom-icons-text.svg'
import { getShowCaseHistory, getIsFetching, getErrorMessage, getCurrentUser} from './selector'
import { validate } from './sign-in.validation.rules'
import './sign-in.styles.scss'
import {dashboardComponentRoutes} from '../inside-dashboard/all-routes'
const SignIn = ({ 
  //properties
  currentUser, isFetching, showCaseHistory, errorMessage, 
  //dispatchers
  doLogin, doDismissError }) => {

  const [passwordShown, setPasswordShown] = useState(false)

  const togglePasswordVisiblity = () => {
    setPasswordShown(passwordShown ? false : true);
  }

  const dismissToast = e => {
    doDismissError()
  }

  const { state } = useLocation()

 
    if(!!currentUser){
      if (showCaseHistory) {
      
        return <Redirect to={'/case-history'} />    
      } 
      else {
      
        return <Redirect to={`/dashboard/${dashboardComponentRoutes['GRAPH_LIST'].route}`} />
      } 
    }
    const LoginButtonWithSpinner = WithSpinner(() =>
        (
          <button type="submit" className="btn-login">Submit</button>
        )
    )

  return (
    <section className="signin-content">
      <div className="mx-5">
        <div className="row">
          <div className="col-md-3 img-responsive">
            <img src={illustration} className="mt-4 illustrations" alt="none"/>            
          </div>
          <div className="col-md-5">&nbsp;</div>
          <div className="col-md-4">
            <div className="form-box ml-3" >
              <div className="d-flex justify-content-center">              
                <img src={formHeaderImg} className="img-fluid mt-0" alt="none"/>
              </div>
              {/* <h2 className="fieldset-title mt-0">Login to Continue</h2> */}

              <Formik
                initialValues={{                  
                  // username: 'connect@healiousglobal.com',
                  // username: 'd.krishnendu84@gmail.com',
                  // username: 'mukherjeeab+05.edu@gmail.com',                  
                  // username: 'mukherjeeab+pat.15@gmail.com',                  
                  // username: 'mukherjeeab+pat.roogi@gmail.com',                  
                  // username: 'krishnendu.work@gmail.com',                  
                  // password: 'abcd1234'
                  // password: 'dOIxTrzg'
                  //prod....
                  username: '',
                  password: ''
                }}
                validationSchema={validate}
                onSubmit={values => {
                  // console.log(values)
                  const {username, password} = values
                  doLogin(username.trim(), password.trim())
                }}
              >
                {formik => (
                  <div style={{borderRadius: '15px'}}>
                    <Form style={{borderRadius:"5px"}}>
                      <div className="form-row">
                        <div className="col form-group">
                          <ATextField label="Username" name="username" type="text" />
                        </div>
                      </div>
                      <div className="form-row">
                        <div className="col form-group">
                          <ATextField label="Password" name="password" type={`${passwordShown  ? 'text' : 'password'}`} 
                                fonticon={`${passwordShown  ? 'eye-slash' : 'eye'}`} groupiconaction={togglePasswordVisiblity}
                                />
                        </div>                    
                      </div>
                      <div className="text-center pt-4">
                        <LoginButtonWithSpinner isLoading={isFetching} defaultHeight={false}/>                                  
                      </div>
                    </Form>
                  </div>
                )}
              </Formik>
              
              <div className="d-flex pt-2 remember-box">
                <div className="form-check">
                  <input type="checkbox" className="form-check-input checkbox" name="remember" />
                  <label htmlFor="remember">Remember me</label>
                </div>
                <span className="ml-auto">
                  <Link to='forgot-password'>Forgot Password?</Link>                  
                </span>
              </div>

              <div className="col-md-12 text-center mt-4">
                <p className="login-txt mb-0">Don’t have an account?&nbsp;
                  <Link to='register'>Sign up</Link> now
                    {/* <a className="clickhere" href="sign-up.html">Sign up</a> now */}
                </p>
              </div>

            </div>
          </div>
        </div>
        <div className="row">
          <div className="col">
              <img src={middleIllustration} className="mt-1  login-bottom-row-1" alt="none"/>            
            </div>
          </div>
        <div className="row">
          <div className="col">
              <img src={bottomIllustration} className="mt-3  login-bottom-row-2" alt="none"/>            
            </div>
          </div>
      </div>
      { !!errorMessage ? <ToastComponent message={errorMessage} onclose={dismissToast}/> : null }

      <br />      
    </section>

  )
}

/**
 * 
 * if any of the Show(Params) is true === show the case history  
 */
const mapStateToProps = state => ({
  currentUser: getCurrentUser(state),
  errorMessage: getErrorMessage(state),
  isFetching: getIsFetching(state),  
  showCaseHistory: getShowCaseHistory(state)
})

const mapDispatchToProps = dispatch => ({
  doLogin: (uname, pswd) => dispatch(authenticateUserAsync({UserId: uname, Password: pswd})),
  doDismissError: () => dispatch(clearAuthenticationState()),
})
export default connect(mapStateToProps, mapDispatchToProps)(SignIn)