import { getSession } from "@auth/solid-start";
import {
  faBadgeCheck,
  faCircleExclamation,
  faPlus,
} from "@fortawesome/pro-regular-svg-icons";
import { useNavigate } from "@solidjs/router";
import { eq } from "drizzle-orm";
import createClient from "openapi-fetch";
import { For, createResource } from "solid-js";
import { getRequestEvent } from "solid-js/web";
import { FontAwesomeIcon } from "~/components/FontAwesomeIcon";
import Layout from "~/components/Layout";
import db from "~/drizzle";
import { accounts } from "~/drizzle/schema";
import { authOptions } from "~/server/auth";
import { paths } from "~/types/discord";
import "../../styles/pages/config.scss";

const initialValue = () => ({
  success: null as boolean | null,
  guilds: [] as {
    id: string;
    name: string;
    icon: string | null | undefined;
  }[],
});

const getPayload = async (): Promise<
  | { success: false; message: string }
  | (ReturnType<typeof initialValue> & { success: true })
> => {
  ("use server");
  const event = getRequestEvent();
  if (!event) return { success: false, message: "No request event!" };

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

  const { DISCORD_ACCESS_TOKEN } = (
    await db
      .selectDistinct({ DISCORD_ACCESS_TOKEN: accounts.access_token })
      .from(accounts)
      .where(eq(accounts.userId, session.user?.id))
      .limit(1)
      .execute()
  )[0];
  if (!DISCORD_ACCESS_TOKEN)
    return { success: false, message: "No discord access token!" };

  const { GET } = createClient<paths>({
    baseUrl: "https://discord.com/api/v10",
  });
  const { data: guilds, error } = await GET("/users/@me/guilds", {
    headers: { Authorization: `Bearer ${DISCORD_ACCESS_TOKEN}` },
  });

  console.log("guilds", guilds);

  if (error) {
    console.log(error);
    return { success: false, message: "Error on discord api request!" };
  }

  return {
    success: true,
    guilds:
      guilds
        ?.filter((e) => parseInt(e.permissions) & (1 << 5))
        .map(({ id, name, icon }) => ({ id, name, icon })) ?? [],
  };
};

function index() {
  const navigator = useNavigate();

  const [payload] = createResource(async () => {
    const payload = await getPayload();

    if (!payload.success) {
      console.log(payload.message, "No success");
      navigator("/", { replace: false });
      return initialValue();
    }
    console.log("success");
    return payload;
  });

  const icons = [faPlus, faCircleExclamation, faBadgeCheck];
  const colors = [undefined, "orange", "green"];

  return (
    <Layout site="config">
      <h3 class="text-center">Configure li&apos;l Judd in</h3>
      <div>
        <For each={payload()?.guilds ?? []}>
          {(guild, i) => (
            <a href={`/config/${guild.id}`} class="flex-row centered">
              <img
                class="guildpfp"
                src={
                  guild.icon
                    ? `https://cdn.discordapp.com/icons/${guild.id}/${guild.icon}.webp?size=240`
                    : "https://cdn.discordapp.com/icons/1040502664506646548/bb5a51c4659cf47bdd942bb11e974da7.webp?size=240"
                }
                alt="Server pfp"
              />
              <h1>{guild.name}</h1>
              <FontAwesomeIcon
                // beat={i() % 3 === 1}
                color={colors[i() % 3]}
                icon={icons[i() % 3]}
                size="xl"
              />
            </a>
          )}
        </For>
      </div>
    </Layout>
  );
}

export default index;
