"use client";

import { redirect } from "next/navigation";
import Link from "next/link";
import { useSession, signIn, signOut } from "next-auth/react";
import { useEffect, useState } from "react";
import axios from "axios";


export default function Home() {
    const { data: session, status } = useSession();
    const [previousUsername, setPreviousUsername] = useState<string>()

    // if (status !== "authenticated") {
    //     redirect('/api/auth/signin?redirectUrl=/');
    // }

    useEffect(() => {
        if (status !== "authenticated" || previousUsername == session.user?.name) {
            console.log("CANCELED")
            return
        }

        setPreviousUsername(session.user?.name as string)

        async function saveAccount() {
            const data = await axios.post("/api/account")
            if (data == null || data == undefined) {
              console.log("ERROR")
            }
        }

        saveAccount().catch(console.error)
    }, [session])

  return (
    <main
      style={{
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        height: "70vh",
      }}
    >
      <div className="header">
        <Link href="/">
          <p className="logo">NextAuth.js</p>
        </Link>
        {session && (
          <Link href="#" onClick={() => signOut()} className="btn-signin">
            Sign out
          </Link>
        )}
        {!session && (
          <Link href="#" onClick={() => signIn()} className="btn-signin">
            Sign in
          </Link>
        )}
      </div>
    </main>
  );
}