import {
  faArrowRightFromBracket,
  faArrowRightToBracket,
  faGear,
} from "@fortawesome/pro-regular-svg-icons";
import { cache, createAsync } from "@solidjs/router";
import { Show } from "solid-js";
import { getRequestEvent } from "solid-js/web";
import { FontAwesomeIcon } from "./FontAwesomeIcon";
import { Li } from "./NavBar";

async function getUser() {
  "use server";

  const event = getRequestEvent();

  return event?.nativeEvent.context.user;
}

const cachedUser = cache(() => getUser(), "userInfo");

function NavUser() {
  const user = createAsync(() => cachedUser());
  const pfp = () => {
    const thisUser = user();
    if (!thisUser?.id) return "";

    return thisUser.image
      ? `https://cdn.discordapp.com/avatars/${thisUser.discord_id}/${thisUser.image}.png`
      : `https://cdn.discordapp.com/embed/avatars/${(parseInt(thisUser.discord_id) >> 22) % 6}.png`;
  };

  return (
    <Show
      when={user()?.id}
      fallback={
        <Li href="/api/auth/login" name="Login" rel="external">
          <FontAwesomeIcon
            class="secondary"
            icon={faArrowRightToBracket}
            size="xl"
          />
        </Li>
      }
    >
      <Li href="/config">
        <div class="swap lower">
          <img class="primary" src={pfp()} alt="User pfp" />
          <FontAwesomeIcon class="secondary" icon={faGear} size="xl" />
        </div>
      </Li>
      <Li href="/api/auth/logout" rel="external">
        <FontAwesomeIcon icon={faArrowRightFromBracket} size="xl" />
      </Li>
    </Show>
  );
}

export default NavUser;
