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";
import Integration from "../data/integration.js";
import DeviceService from "../services/device-service.js";

const [integration, setIntegration] = createSignal(new Integration());
const eventEmitter = new EventEmitter();
const INTEGRATION_DELETED_EVENT = "success";

function DeleteIntegrationModal(props) {
  const [error, setError] = createSignal("");

  async function handleDeleteIntegration() {
    try {
      await DeviceService.deleteIntegration(integration().getId());
    } catch (e) {
      setError(e.message);
      throw e;
    }
    DeleteIntegrationModal.Handler.hide();
    eventEmitter.dispatchEvent(INTEGRATION_DELETED_EVENT, integration);
  }

  return (
    <Modal
      ref={props.ref}
      id="deleteIntegrationModal"
      modalTitle="Delete integration"
      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 integration {integration().getName()}?
          </span>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
          Cancel
        </button>
        <button
          type="button"
          onClick={handleDeleteIntegration}
          class="btn btn-danger"
        >
          Delete
        </button>
      </div>
    </Modal>
  );
}

DeleteIntegrationModal.Handler = new ModalHandler();
DeleteIntegrationModal.setIntegration = setIntegration;
DeleteIntegrationModal.onIntegrationDeleted = (callback) =>
  eventEmitter.on(INTEGRATION_DELETED_EVENT, callback);

export default DeleteIntegrationModal;
