import { getSession } from "@auth/solid-start";
import { signIn, signOut } from "@auth/solid-start/client";
import {
  faArrowRightFromBracket,
  faArrowRightToBracket,
  faGear,
} from "@fortawesome/pro-regular-svg-icons";
import { eq } from "drizzle-orm";
import { Show, createResource } from "solid-js";
import { getRequestEvent } from "solid-js/web";
import db from "~/drizzle";
import { users } from "~/drizzle/schema";
import { authOptions } from "~/server/auth";
import { FontAwesomeIcon } from "./FontAwesomeIcon";
import { Li } from "./NavBar";

const initialUser = {
  id: "",
  name: null as string | null,
  email: "",
  emailVerified: null as Date | null,
  image: null as string | null,
};

async function getUser() {
  "use server";

  const event = getRequestEvent();
  if (!event)
    return { success: false, message: "No request event!", ...initialUser };

  const session = await getSession(event.request, authOptions);
  if (!session?.user?.id)
    return { success: false, message: "No user with id!", ...initialUser };

  const user = (
    await db
      .selectDistinct()
      .from(users)
      .where(eq(users.id, session.user?.id))
      .limit(1)
      .execute()
  )[0];

  return { success: true, message: "", ...user };
}

function NavUser() {
  const [user] = createResource(async () => {
    const user = await getUser();

    if (!user.success) console.error("userInfo", user.message);

    return user;
  });

  return (
    <Show
      when={user()?.id}
      fallback={
        <Li
          href="#"
          name="Login"
          action={() => signIn("discord", { callbackUrl: "/config" })}
        >
          <FontAwesomeIcon
            class="secondary"
            icon={faArrowRightToBracket}
            size="xl"
          />
        </Li>
      }
    >
      <Li href="/config">
        <div class="swap lower">
          <img class="primary" src={user()?.image ?? ""} alt="User pfp" />
          <FontAwesomeIcon class="secondary" icon={faGear} size="xl" />
        </div>
      </Li>
      <Li href="#" action={() => signOut({ callbackUrl: "/" })}>
        <FontAwesomeIcon icon={faArrowRightFromBracket} size="xl" />
      </Li>
    </Show>
  );
}

export default NavUser;
