"use client";
import { useSession } from "muzak/contexts/SessionContext";
import { useState, useEffect } from "react";
import { useAuth } from "react-oidc-context";
import { getUser } from "muzak/data/fetcher";
import { Nunito } from "next/font/google";

const nunito = Nunito({
  weight: "900",
  subsets: ["latin"],
});

export default function Session() {
  const auth = useAuth();
  const { sessionId, setSessionId } = useSession();
  const user = getUser();
  const [sessionSocket, setSessionSocket] = useState<WebSocket | null>(null);

  function connect() {
    console.log(`ik ben ${user.profile.nickname}`);
    console.log(sessionSocket?.readyState);
    if (sessionSocket?.readyState === WebSocket.OPEN) {
      console.log("socket is open");
      sessionSocket.send(
        JSON.stringify({
          action: "login",
          userr: user.profile.nickname,
          token: user.access_token,
        }),
      );
    }
  }

  useEffect(() => {
    if (sessionId) {
      const socket = new WebSocket(
        `${process.env.NEXT_PUBLIC_WS_HOST}/voting/session/${sessionId}/`,
      );
      setSessionSocket(socket);
    }
  }, [sessionId]);
  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-24">
      <div>
        <h1
          className={`${nunito.className} text-outline text-[42px] tracking-tighter text-yellow-500`}
        >
          LOGIN
        </h1>
      </div>
      <div className="mb-12 flex flex-col items-center justify-between gap-4 rounded-md bg-blue-950/80 p-8">
        <h1 className="text-xl text-white">{user.profile.nickname}</h1>
        <button
          className="rounded-md bg-blue-500 px-4 py-2 text-white hover:bg-blue-600"
          onClick={connect}
        >
          Connect
        </button>
      </div>
    </main>
  );
}
