import { useContext, useState } from "react";
import { useHistory } from "react-router-dom";
import classes from "./LoginForm.module.css";

import TextField from "@material-ui/core/TextField";
import Button from "@material-ui/core/Button";
import CircularProgress from "@material-ui/core/CircularProgress";

import Card from "../Card/Card";
import Logo from "../Logo/Logo";
import AuthContext from "../../contexts/AuthContext";
import * as api from "../../api/api";

const LoginForm = () => {
  const authCtx = useContext(AuthContext);

  const history = useHistory();

  const [isLoading, setIsLoading] = useState(false);
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [formRole, setformRole] = useState("Customer");
  const [notActiveRole, setnotActiveRole] = useState("Employee");
  const [authError, setauthError] = useState({ state: false, msg: "" });

  const switchRoles = () => {
    if (formRole === "Customer") {
      setformRole("Employee");
      setnotActiveRole("Customer");
    }
    if (formRole === "Employee") {
      setformRole("Customer");
      setnotActiveRole("Employee");
    }
  };

  const onSubmitHandler = (e) => {
    setIsLoading(true);

    const roleParam = formRole.toLowerCase();

    e.preventDefault();
    api
      .login(username, password, roleParam)
      .then((data) => {
        authCtx.login(data.accessToken, data.refreshToken, roleParam);
        history.replace("/home");
      })
      .catch((e) => {
        setauthError({ state: true, msg: e });
      })
      .finally(() => {
        setIsLoading(false);
      });
  };

  return (
    <Card>
      <div className={classes.simpleCard}>
        <Logo />
        <h1>{formRole} Login</h1>
        <form className={classes.loginForm} onSubmit={onSubmitHandler}>
          <TextField
            className={classes.textfield}
            name="username"
            label="Username"
            value={username}
            required
            onChange={(e) => setUsername(e.target.value)}
          />
          <br />

          <TextField
            className={classes.textfield}
            name="password"
            label="Password"
            type="password"
            value={password}
            required
            onChange={(e) => setPassword(e.target.value)}
          />
          <div>
            <Button
              color="primary"
              type="submit"
              variant="contained"
              className={classes.submitButton}
            >
              Submit
            </Button>
          </div>
          {isLoading && <CircularProgress />}

          {authError.state && (
            <b style={{ color: "red", margin: "20px" }}>
              {authError.msg.toString()}
            </b>
          )}
        </form>
        <Button onClick={switchRoles} type="submit" variant="outlined">
          Go to {notActiveRole} Login
        </Button>
      </div>
    </Card>
  );
};

export default LoginForm;
