import { createSignal, mergeProps } from "solid-js";
import UserService from "../services/user-service";
import Spinner from "../modules/spinner";

const IDLE = "idle";
const LOGGING_IN = "logging-in";
const LOGIN_FAILED = "login-failed";

function LoginView(props) {
  props = mergeProps({ onLogin: () => {} }, props);
  let usernameInput;
  let passwordInput;

  const [status, setStatus] = createSignal(IDLE);

  async function handleLogin() {
    const username = usernameInput.value;
    const password = passwordInput.value;

    setStatus(LOGGING_IN);
    try {
      await UserService.login({ username, password });
    } catch (e) {
      setStatus(LOGIN_FAILED);
      return;
    }

    const info = await UserService.getUserInfo();
    if (info) {
      props.onLogin(info);
    }
  }
  
  function handleKeyDown(event) {
    if (event.key === "Enter") {
      handleLogin();
    }
  }

  return (
    <div
      class="d-flex align-items-center justify-content-center"
      style="width: 100vw; height: 100vh;"
    >
      <div
        class="container bg-body-tertiary p-3 rounded"
        style="max-width: 30em"
      >
        <h4 class="mb-3">Login</h4>
        <Show when={status() === LOGIN_FAILED}>
          <div class="alert alert-danger" role="alert">
            Login fehlgeschlagen
          </div>
        </Show>

        <div class="mb-3">
          <label for="usernameInput" class="form-label">
            Nutzername
          </label>
          <input
            ref={usernameInput}
            type="user"
            class="form-control"
            id="usernameInput"
            onKeyDown={handleKeyDown}
          />
        </div>
        <div class="mb-3">
          <label for="passwordInput" class="form-label">
            Passwort
          </label>
          <input
            ref={passwordInput}
            type="password"
            class="form-control"
            id="passwordInput"
            onKeyDown={handleKeyDown}
          />
        </div>
        <button type="submit" class="btn btn-primary" onClick={handleLogin}>
          <Show when={status() === LOGGING_IN}>
            <Spinner class="spinner-border-sm me-2" />
          </Show>
          Login
        </button>
      </div>
    </div>
  );
}

export default LoginView;

