import React from 'react';
import {
  Alert,
  Button,
  FormControl,
  Glyphicon,
  Panel,
  FormGroup,
  ControlLabel,
} from 'react-bootstrap';
import UI from '../../config/ui/config';
import ErrorUserMessage from '../UserMessages/ErrorUserMessage';
import AnonymousSignIn from './AnonymousSignIn';
import { useSelector, useDispatch } from 'react-redux';
import { doSignIn } from '../../actions/login';
import { useForm } from 'react-hook-form';

function LoginForm(props) {
  const { plugin } = props;
  const user = useSelector((state) => state.user);

  const { register, handleSubmit } = useForm();
  const dispatch = useDispatch();

  return (
    <Panel className="tab-panel-fix" style={{ padding: '20px 0 ' }}>
      <form
        className="container-fluid"
        onSubmit={handleSubmit((data) => {
          dispatch(doSignIn(plugin, data.username, data.password));
        })}
      >
        {UI.loginForm.header && (
          <p className="text-info" style={{ textAlign: 'left' }}>
            {UI.loginForm.header}
          </p>
        )}
        {user.error && <ErrorUserMessage text={user.error} />}
        {user.isSessionExpired && (
          <Alert bsStyle="warning">Session expired</Alert>
        )}

        <FormGroup controlId="username">
          <ControlLabel>{UI.loginForm.usernameLabel}</ControlLabel>
          <FormControl
            inputRef={register({ required: true })}
            type="text"
            name="username"
            autoFocus
            required
          />
        </FormGroup>

        <FormGroup controlId="password">
          <ControlLabel>Password</ControlLabel>
          <FormControl
            inputRef={register({ required: true })}
            type="password"
            name="password"
            required
          />
        </FormGroup>

        <Button
          style={{ marginTop: 5, width: '100%' }}
          type="submit"
          bsStyle="primary"
        >
          <Glyphicon glyph="log-in" style={{ marginRight: 10 }} />
          {user.isAuthenticating ? 'Signing in...' : 'Sign in'}
        </Button>
      </form>

      <AnonymousSignIn />
    </Panel>
  );
}

export default LoginForm;
