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

const [user, setUser] = createSignal(new User());
const eventEmitter = new EventEmitter();
const USER_UPDATED_EVENT = "user-updated";

function UserSettingsModal(props) {
  const [isAdmin, setAdmin] = createSignal(false);
  const [error, setError] = createSignal("");
  const [userInfo] = createResource(() => UserService.getUserInfo());
  let canEditAdmin = createMemo(
    () => userInfo.loading || user().getId() !== userInfo().user_id
  );
  createEffect(() => setAdmin(user().isAdmin()));

  async function handleSaveSettings() {
    try {
      await UserService.updateUser(user().getId(), { isAdmin: isAdmin() });
    } catch (error) {
      setError(error.message);
      return;
    }
    UserSettingsModal.Handler.hide();
    eventEmitter.dispatchEvent(USER_UPDATED_EVENT, user());
  }

  return (
    <Modal
      ref={props.ref}
      id="userSettingsModal"
      modalTitle={`Settings for ${user().getUsername()}`}
      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="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()}
              disabled={!canEditAdmin()}
              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={handleSaveSettings}
          class="btn btn-primary"
        >
          Save
        </button>
      </div>
    </Modal>
  );
}

UserSettingsModal.Handler = new ModalHandler();
UserSettingsModal.setUser = setUser;
UserSettingsModal.onUserUpdated = (callback) =>
  eventEmitter.on(USER_UPDATED_EVENT, callback);

export default UserSettingsModal;
