import React, { useState } from 'react'
import { connect } from 'react-redux'
import { Redirect } from 'react-router'
import { bindActionCreators, Dispatch } from 'redux'

import ButtonWithProgress from '@agiliza/components/atoms/ButtonWithProgress'
import TextFieldWithIcon from '@agiliza/components/atoms/TextFieldWithIcon'
import { StoreState } from '@agiliza/redux'
import { isAuthenticated } from '@agiliza/redux/session/selectors'
import { actions } from '@agiliza/redux/ui/login'
import { isFetching } from '@agiliza/redux/ui/login/selectors'
import InputAdornment from '@material-ui/core/InputAdornment'
import Typography from '@material-ui/core/Typography'
import AccountCircle from '@material-ui/icons/AccountCircle'

import { useStyles } from './styles'

import type { RouteComponentProps } from 'react-router'
type BaseProps = RouteComponentProps

interface Props extends BaseProps {
  authenticated: boolean
  fetching: boolean
  loginRequest: typeof actions.login
}

const Login = (props: Props) => {
  const { loginRequest, authenticated, fetching } = props

  const classes = useStyles()

  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')

  const handleLogin = () => {
    loginRequest({ username, password })
  }

  if (authenticated) {
    return <Redirect to="/" />
  }

  return (
    <div className={classes.container}>
      {/* <div className={classes.logo} /> */}
      <div className={classes.formContainer}>
        <Typography align="center" className={classes.title} color="primary">
          {process.env.APP_TITLE}
        </Typography>
        <form className={classes.form} onKeyDown={(evt) => evt.keyCode === 13 && handleLogin()}>
          <TextFieldWithIcon
            autoFocus
            required
            value={username}
            onChange={(evt) => setUsername(evt.target.value)}
            label="Usuário"
            className={classes.usernameTxtField}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <AccountCircle />
                </InputAdornment>
              ),
            }}
          />
          <TextFieldWithIcon required value={password} onChange={(evt) => setPassword(evt.target.value)} label="Senha" type="password" />
        </form>
        <ButtonWithProgress disabled={!username} color="secondary" fetching={fetching} onClick={handleLogin}>
          Entrar
        </ButtonWithProgress>
      </div>
      {/* <PopoverVersion service={service} /> */}
    </div>
  )
}

const mapStateToProps = (state: StoreState) => ({
  authenticated: isAuthenticated(state.session),
  fetching: isFetching(state.ui.login),
})

const mapDispatchToProps = (dispatch: Dispatch) =>
  bindActionCreators(
    {
      loginRequest: actions.login,
    },
    dispatch
  )

export default connect(mapStateToProps, mapDispatchToProps)(Login)
