import { createEffect, createSignal } from "solid-js";
import Modal from "./modal.jsx";
import UserService from "../services/user-service.js";
import EventEmitter from "../tools/event-emitter.js";
import ValidatedTextInput from "../modules/validated-text-input.jsx";
import ModalHandler from "./modal-handler.js";

const [users, setUsers] = createSignal([]);
const eventEmitter = new EventEmitter();
const USER_CREATED_EVENT = "success";

const MIN_PASSWORD_LENGTH = 6;

function CreateUserModal(props) {
  const [username, setUsername] = createSignal("");
  const [isUsernameValid, setUsernameValid] = createSignal(true);
  const [password, setPassword] = createSignal("");
  const [isPasswordValid, setPasswordValid] = createSignal(true);
  const [isAdmin, setAdmin] = createSignal(false);
  const [error, setError] = createSignal("");

  createEffect(() => setUsernameValid(checkIfUsernameValid(username())));
  createEffect(() => setPasswordValid(checkIfPasswordValid(password())));

  function checkIfUsernameValid(name) {
    for (let user of users()) {
      if (user.getUsername() !== name) continue;
      return false;
    }
    return true;
  }

  function checkIfPasswordValid(password) {
    return password.length >= MIN_PASSWORD_LENGTH;
  }

  async function handleCreateUser() {
    let user;
    try {
      user = await UserService.createUser({
        username: username(),
        password: password(),
        isAdmin: isAdmin(),
      });
    } catch (e) {
      setError(e.message);
      return;
    }
    setUsername("");
    setPassword("");
    CreateUserModal.Handler.hide();
    eventEmitter.dispatchEvent(USER_CREATED_EVENT, user);
  }

  return (
    <Modal
      ref={props.ref}
      id="createUserModal"
      modalTitle="New User"
      centered={true}
    >
      <div class="modal-body">
        <Show when={error() !== ""}>
          <div class="alert alert-danger" role="alert">
            {error()}
          </div>
        </Show>
        <div class="mb-3 row">
          <label for="new_username" class="col-form-label col-sm-2">
            Username
          </label>
          <ValidatedTextInput
            class="col-sm-10"
            id="new_username"
            valid={isUsernameValid()}
            value={username()}
            onInput={(e) => setUsername(e.target.value)}
            errorText={"Username already exists"}
          />
        </div>
        <div class="mb-3 row">
          <label for="user_password" class="col-form-label col-sm-2">
            Password
          </label>
          <ValidatedTextInput
            class="col-sm-10"
            id="user_password"
            type="password"
            valid={isPasswordValid()}
            value={password()}
            onInput={(e) => setPassword(e.target.value)}
            errorText={"Invalid password"}
          />
        </div>
        <div class="mb-3 row">
          <label for="is_admin" class="col-form-label col-sm-2">
            Admin
          </label>
          <div class="col-sm-10 d-flex align-items-center">
            <input
              id="is_admin"
              type="checkbox"
              class="form-check-input"
              checked={isAdmin()}
              onChange={() => setAdmin(!isAdmin())}
            />
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
          Cancel
        </button>
        <button
          type="button"
          onClick={handleCreateUser}
          class="btn btn-primary"
          disabled={!isUsernameValid() && !isPasswordValid()}
        >
          Create
        </button>
      </div>
    </Modal>
  );
}

CreateUserModal.Handler = new ModalHandler();
CreateUserModal.setUsers = setUsers;
CreateUserModal.onUserCreated = (callback) =>
  eventEmitter.on(USER_CREATED_EVENT, callback);

export default CreateUserModal;
