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

const eventEmitter = new EventEmitter();
const DEVICE_CREATED_EVENT = "success";
const MIN_NAME_LENGTH = 3;

function CreateDeviceModal(props) {
  const [name, setName] = createSignal("");
  const [isNameValid, setNameValid] = createSignal(true);
  const [description, setDescription] = createSignal("");
  const [isDescriptionValid, setDescriptionValid] = createSignal(true);
  const [error, setError] = createSignal("");
  
  createEffect(() => setNameValid(checkIfNameValid(name())));
  createEffect(() => setDescriptionValid(checkIfDescriptionValid(description())));
  
  function checkIfNameValid(name) {
    return name.length >= MIN_NAME_LENGTH;
  }
  
  function checkIfDescriptionValid(description) {
    return true;
  }

  async function handleCreateDevice() {
    let device;
    try {
      device = await DeviceService.createDevice({
        name: name(),
        description: description(),
      });
    } catch (e) {
      setError(e.message);
      return;
    }
    setName("");
    setDescription("");
    CreateDeviceModal.Handler.hide();
    eventEmitter.dispatchEvent(DEVICE_CREATED_EVENT, device);
  }

  return (
    <Modal
      ref={props.ref}
      id="createDeviceModal"
      modalTitle="New Device"
      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_device_name" class="col-form-label col-sm-2">
            Name
          </label>
          <ValidatedTextInput
            class="col-sm-10"
            id="new_device_name"
            valid={isNameValid()}
            value={name()}
            onInput={(e) => setName(e.target.value)}
            errorText={"Device name too short"}
          />
        </div>
        <div class="mb-3 row">
          <label for="description" class="col-form-label col-sm-2">
            Description
          </label>
          <ValidatedTextInput
            class="col-sm-10"
            id="description"
            valid={isDescriptionValid()}
            value={description()}
            onInput={(e) => setDescription(e.target.value)}
            errorText={"Invalid description"}
          />
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
          Cancel
        </button>
        <button
          type="button"
          onClick={handleCreateDevice}
          class="btn btn-primary"
          disabled={!isNameValid() && !isDescriptionValid()}
        >
          Create
        </button>
      </div>
    </Modal>
  );
}

CreateDeviceModal.Handler = new ModalHandler();
CreateDeviceModal.onDeviceCreated = (callback) =>
  eventEmitter.on(DEVICE_CREATED_EVENT, callback);

export default CreateDeviceModal;
