import React from "react";
import { useState } from "react/cjs/react.development";
import "../../App.css";
import Footer from "../../Footer";
import InputField from "../InputField";
import SubmitField from "../SubmitField";
import { Redirect } from "react-router";
import { login, useAuth } from "../../auth/AuthProvider";
import ErrorMessage from "../ErrorMessage";

export default function Login() {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [errorMessage, setErrorMessage] = useState("");

  const onSubmitClick = (e) => {
    e.preventDefault();
    let opts = {
      username: username,
      password: password,
    };
    fetch("/api/login", {
      method: "post",
      body: JSON.stringify(opts),
    }).then((response) => {
      if (response.status === 401) {
        response.json().then((resp) => {
          setErrorMessage(resp.message);
        });
      } else {
        response.json().then((token) => {
          login(token);
        });
      }
    });
  };

  const handleUsernameChange = (e) => {
    setUsername(e.target.value);
  };

  const handlePasswordChange = (e) => {
    setPassword(e.target.value);
  };

  const [isLoggedIn] = useAuth();

  return (
    <>
      <div className="sitePage">
        <h1>Login</h1>
        {!isLoggedIn ? (
          <form action="#">
            <InputField
              LabelName="Benutzername"
              onChange={handleUsernameChange}
              InputType="text"
              InputName="username"
              InputPlaceHolder="Benutzername"
            />
            <InputField
              LabelName="Passwort"
              InputType="password"
              onChange={handlePasswordChange}
              InputName="password"
              InputPlaceHolder="Passwort"
            />
            <br />
            <ErrorMessage message={errorMessage} />
            <SubmitField onClick={onSubmitClick} LabelName="Einloggen" />
          </form>
        ) : (
          <>
            <Redirect to="/behavior" />
          </>
        )}
      </div>
      <Footer />
    </>
  );
}
