import {
  createEffect,
  createSignal,
  Show,
  createResource,
  onMount,
} from "solid-js";
import Modal from "./modal.jsx";
import ModalHandler from "./modal-handler.js";
import DeviceService from "../services/device-service.js";

function ShowRegistrationCodeModal(props) {
  const [error, setError] = createSignal("");
  const [code, { mutate, refetch }] = createResource(async () =>
    DeviceService.getRegistrationCode()
  );

  onMount(() => {
    ShowRegistrationCodeModal.Handler.onHidden(() => mutate(null));
    ShowRegistrationCodeModal.Handler.onShow(() => refetch());
  });

  function handleClose() {
    ShowRegistrationCodeModal.Handler.hide();
  }

  return (
    <Modal
      ref={props.ref}
      id="showRegistrationCodeModal"
      modalTitle="Register"
      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_name" class="col-form-label col-sm-4">
            Enter this code on the device:
          </label>
          <div class="col-sm-8">
            <input
              class="form-control font-monospace"
              type="text"
              id="new_name"
              value={code()}
              readonly
            />
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" onClick={handleClose} class="btn btn-primary">
          OK
        </button>
      </div>
    </Modal>
  );
}

ShowRegistrationCodeModal.Handler = new ModalHandler();

export default ShowRegistrationCodeModal;
