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 User from "../data/user.js";
import ValidatedTextInput from "../modules/validated-text-input.jsx";
import ModalHandler from "./modal-handler.js";

const [user, setUser] = createSignal(new User());
const eventEmitter = new EventEmitter();
const USER_DELETED_EVENT = "success";

function DeleteUserModal(props) {
  const [username, setUsername] = createSignal("");
  const [isUsernameValid, setUsernameValid] = createSignal(true);
  const [error, setError] = createSignal("");

  createEffect(() => setUsernameValid(checkIfUsernameValid(username())));

  function checkIfUsernameValid(name) {
    return name === user().getUsername();
  }

  async function handleDeleteUser() {
    try {
      await UserService.deleteUser(user().getId());
    } catch (e) {
      setError(e.message);
      throw e;
    }
    DeleteUserModal.Handler.hide();
    eventEmitter.dispatchEvent(USER_DELETED_EVENT, user);
  }

  return (
    <Modal
      ref={props.ref}
      id="deleteUserModal"
      modalTitle="Delete 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">
          <span>
            Do you really want to delete the user {user().getUsername()}?
          </span>
        </div>
        <div class="mb-3">
          <label for="del_username" class="col-form-label">
            Type <b>{user().getUsername()}</b> to confirm:
          </label>
          <ValidatedTextInput
            id="del_username"
            valid={isUsernameValid()}
            value={username()}
            onInput={(e) => setUsername(e.target.value)}
            errorText={"Wrong input"}
          />
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
          Cancel
        </button>
        <button
          type="button"
          onClick={handleDeleteUser}
          class="btn btn-danger"
          disabled={!isUsernameValid()}
        >
          Delete
        </button>
      </div>
    </Modal>
  );
}

DeleteUserModal.Handler = new ModalHandler();
DeleteUserModal.setUser = setUser;
DeleteUserModal.onUserDeleted = (callback) =>
  eventEmitter.on(USER_DELETED_EVENT, callback);

export default DeleteUserModal;
