import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import Layout from "../components/Layout.js";
import { useSessionContext } from "../context/session.context.js";
import { getUser, logout, logoutRequest } from "../requests/requests.users.js";

export default function Dashboard() {
  const router = useRouter()
  const [user, setUser] = useState()
  const {isLogin} = useSessionContext()
  useEffect(() => {
    if (!isLogin) {
      router.push({pathname: '/login'}, undefined, {shallow: true})
    } else {
      getUser(localStorage.getItem('token')).then((res) => {
        setUser({...res})
      })
    }
    return () => {
      setUser()
    }
  }, [])
  return <Layout>
    logged as {user && user.username}
    <button onClick={() => {
      logoutRequest(localStorage.getItem('token')).then((r) => {
        localStorage.clear()
        router.push({pathname: '/login'})
      })
    }}>Logout</button>
  </Layout>
}