import { Show, createEffect, createResource, createSignal } from "solid-js";
import ChangePasswordSettings from "../modules/settings/change-password";
import UserList from "../modules/settings/users-list";
import UserService from "../services/user-service";

function SettingsView(props) {
  const ACCOUNT_TAB = "account";
  const USERS_TAB = "users";

  const [activeTab, setActiveTab] = createSignal(ACCOUNT_TAB);
  const [userInfo] = createResource(() => UserService.getUserInfo());

  const tabs = [
    {
      id: ACCOUNT_TAB,
      text: "Account",
      render: renderAccountSettings,
    },
    {
      id: USERS_TAB,
      text: "Users",
      adminOnly: true,
      render: () => renderUserSettings,
    },
  ];

  function renderAccountSettings() {
    return (
      <>
        <ChangePasswordSettings />
      </>
    );
  }

  function renderUserSettings() {
    return (
      <>
        <UserList />
      </>
    );
  }

  return (
    <div class={"flex-fill p-3 d-flex flex-column " + props.class}>
      <div class="d-flex align-items-center mb-3">
        <h3 class="me-3 mb-0">Settings</h3>
        <For each={tabs}>
          {(tab) => (
            <Show
              when={!tab.adminOnly || (!userInfo.loading && userInfo().is_admin)}
            >
              <button
                class={
                  "btn ms-2" +
                  (activeTab() === tab.id ? " btn-secondary" : " btn-dark")
                }
                onClick={() => setActiveTab(tab.id)}
              >
                {tab.text}
              </button>
            </Show>
          )}
        </For>
      </div>
      <For each={tabs}>
        {(tab) => <Show when={tab.id === activeTab()}>{tab.render()}</Show>}
      </For>
    </div>
  );
}

export default SettingsView;
