import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import { loginUser, recoverPassword, registerUser } from "../api/userApi";
import Message from "../components/Message";

var emptyForm = {
  username: "",
  password: "",
  newPassword: "",
};

function Login(props) {
  var formState = useState(emptyForm);
  var formData = formState[0];
  var setFormData = formState[1];
  var modeState = useState("login");
  var mode = modeState[0];
  var setMode = modeState[1];
  var messageState = useState("");
  var message = messageState[0];
  var setMessage = messageState[1];
  var messageTypeState = useState("");
  var messageType = messageTypeState[0];
  var setMessageType = messageTypeState[1];
  var navigate = useNavigate();

  function handleChange(event) {
    var newFormData = Object.assign({}, formData);
    newFormData[event.target.name] = event.target.value;
    setFormData(newFormData);
  }

  function handleSubmit(event) {
    event.preventDefault();
    setMessage("");
    var username = formData.username.trim();

    if (mode === "register") {
      registerUser({
          username: username,
          password: formData.password,
        })
        .then(function (response) {
        props.setUser(response.data.user);
        navigate("/");
        })
        .catch(function (error) {
          setMessageType("error");
          setMessage(error.response && error.response.data ? error.response.data.message : "Login request failed. Check that the backend server and MongoDB are running.");
        });
      return;
    }

    if (mode === "recover") {
      recoverPassword({
        username: username,
        newPassword: formData.newPassword,
      })
        .then(function (response) {
        setMessageType("success");
        setMessage(response.data.message);
        setMode("login");
        })
        .catch(function (error) {
          setMessageType("error");
          setMessage(error.response && error.response.data ? error.response.data.message : "Login request failed. Check that the backend server and MongoDB are running.");
        });
      return;
    }

    loginUser({
      username: username,
      password: formData.password,
    })
      .then(function (response) {
        props.setUser(response.data.user);
        navigate("/");
      })
      .catch(function (error) {
        setMessageType("error");
        setMessage(error.response && error.response.data ? error.response.data.message : "Login request failed. Check that the backend server and MongoDB are running.");
      });
  }

  return (
    <div className="flex min-h-screen items-center justify-center bg-slate-50 p-4 text-blue-900">
      <div className="w-full max-w-md rounded-md border border-slate-200 bg-white p-6">
        <h1 className="text-2xl font-bold">SUPPLY CHAIN MANAGEMENT SYSTEM</h1>
        <p className="mt-2 text-sm text-blue-800">SupplyNet Ltd - Musanze District</p>

        <div className="mt-5 flex rounded-md border border-blue-900">
          <button className={"flex-1 px-3 py-2 " + (mode === "login" ? "bg-blue-900 text-slate-50" : "bg-slate-50")} onClick={function () { setMode("login"); }}>
            Login
          </button>
          <button className={"flex-1 px-3 py-2 " + (mode === "register" ? "bg-blue-900 text-slate-50" : "bg-slate-50")} onClick={function () { setMode("register"); }}>
            Create User
          </button>
        </div>

        <button className="mt-3 text-sm font-semibold text-blue-900" onClick={function () { setMode("recover"); }}>
          Password Recovery
        </button>

        <form className="mt-5" onSubmit={handleSubmit}>
          <Message type={messageType} text={message} />

          <label className="mb-2 block text-sm font-semibold">Username</label>
          <input
            className="mb-4 w-full rounded-md border border-slate-200 bg-slate-50 px-3 py-2 outline-blue-900"
            name="username"
            value={formData.username}
            onChange={handleChange}
            required
            autoComplete="username"
          />

          {mode !== "recover" && (
            <>
              <label className="mb-2 block text-sm font-semibold">Password</label>
              <input
                className="mb-4 w-full rounded-md border border-slate-200 bg-slate-50 px-3 py-2 outline-blue-900"
                name="password"
                type="password"
                value={formData.password}
                onChange={handleChange}
                required
                minLength="6"
                autoComplete={mode === "register" ? "new-password" : "current-password"}
              />
            </>
          )}

          {mode === "recover" && (
            <>
              <label className="mb-2 block text-sm font-semibold">New Password</label>
              <input
                className="mb-4 w-full rounded-md border border-slate-200 bg-slate-50 px-3 py-2 outline-blue-900"
                name="newPassword"
                type="password"
                value={formData.newPassword}
                onChange={handleChange}
                required
                minLength="6"
                autoComplete="new-password"
              />
            </>
          )}

          <button className="w-full rounded-md bg-blue-900 px-4 py-2 font-semibold text-slate-50">
            {mode === "register" ? "Create User" : mode === "recover" ? "Recover Password" : "Login"}
          </button>
        </form>
      </div>
    </div>
  );
}

export default Login;
