import {
  createEffect,
  createSignal,
  Match,
  mergeProps,
  onCleanup,
  Switch,
} from "solid-js";

import DevicesListView from "./devices-list-view";
import IntegrationListView from "./integration-list-view";
import UrlUtils from "../../tools/url-utils";
import IntegrationView from "./integration-view";

function DevicesView(props) {
  props = mergeProps({ onIntegrationClicked: () => {} }, props);
  const DEVICES_LIST_VIEW = "devices";
  const INTEGRATION_LIST_VIEW = "integrations";
  const INTEGRATION_VIEW = "integration";
  const VIEWS = [DEVICES_LIST_VIEW, INTEGRATION_LIST_VIEW, INTEGRATION_VIEW];

  const [currentView, setCurrentView] = createSignal(INTEGRATION_LIST_VIEW);

  createEffect(() => {
    let url = UrlUtils.getUrl();
    url = UrlUtils.addQueryParameter(url, "tab", currentView());
    UrlUtils.setUrl(url);
  });

  onCleanup(() => {
    window.removeEventListener("popstate", setViewFromUrl);
  });

  setViewFromUrl();
  window.addEventListener("popstate", setViewFromUrl);

  function setViewFromUrl() {
    let view = UrlUtils.getQueryParameter("tab");
    if (!view) return;
    if (!VIEWS.includes(view)) return;
    setCurrentView(view);
  }

  function handleIntegrationClicked(integration) {
    IntegrationView.setIntegration(integration);
    setCurrentView(INTEGRATION_VIEW);
  }

  function Navigation() {
    return (
      <div class="d-flex flex-row flex-fill">
        <button
          class={
            "btn me-2 mb-3" +
            (currentView() === INTEGRATION_LIST_VIEW
              ? " btn-secondary"
              : " btn-dark")
          }
          onClick={() => setCurrentView(INTEGRATION_LIST_VIEW)}
        >
          <i class="bi bi-gear me-2"></i>
          Integrations
        </button>
        <button
          class={
            "btn me-2 mb-3" +
            (currentView() === DEVICES_LIST_VIEW
              ? " btn-secondary"
              : " btn-dark")
          }
          onClick={() => setCurrentView(DEVICES_LIST_VIEW)}
        >
          <i class="bi bi-tv me-2"></i>
          Devices
        </button>
      </div>
    );
  }

  return (
    <div
      class={
        "d-flex flex-column overflow-hidden " +
        props.class
      }
    >
      <Switch>
        <Match when={currentView() === INTEGRATION_LIST_VIEW}>
          <IntegrationListView
            navigation={<Navigation />}
            onIntegrationClicked={handleIntegrationClicked}
          />
        </Match>
        <Match when={currentView() === DEVICES_LIST_VIEW}>
          <DevicesListView navigation={<Navigation />} />
        </Match>
        <Match when={currentView() === INTEGRATION_VIEW}>
          <IntegrationView />
        </Match>
      </Switch>
    </div>
  );
}

export default DevicesView;
