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

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

  const [errorMessage, setErrorMessage] = useState("");

  const [isStatusOk, setIsStatusOk] = useState("");

  const [isLoggedIn] = useAuth();

  const onSubmitClick = (e) => {
    e.preventDefault();
    let opts = {
      username: username,
      password: password,
    };
    fetch("/api/register", {
      method: "post",
      body: JSON.stringify(opts),
    }).then((response) => {
      if (response.status === 409) {
        /* 
        then is needed twice to get rid of the javascript Promise thing
        */
        setIsStatusOk(false);
        response.json().then((resp2) => {
          setErrorMessage(resp2.message);
        });
      } else if (response.status === 200) {
        response.json().then((resp) => {
          fetch("/api/login", {
            method: "post",
            body: JSON.stringify(opts),
          }).then((response) => {
            response.json().then((token) => {
              login(token);
            });
          });
        });
        setIsStatusOk(true);
      }
    });
  };

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

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

  return (
    <>
      <div className="sitePage">
        <h1>Registrierung</h1>
        <form>
          <InputField
            LabelName="Benutzername"
            InputType="text"
            onChange={handleUsernameChange}
            InputName="username"
          />
          {!isStatusOk && <ErrorMessage message={errorMessage} />}
          <InputField
            LabelName="Passwort"
            InputType="password"
            onChange={handlePasswordChange}
            InputName="password"
          />
          <br />
          <SubmitField onClick={onSubmitClick} LabelName="Registrieren" />
        </form>

        {isLoggedIn && <Redirect to="/umfrage" />}
      </div>
      <Footer />
    </>
  );
}
