"use client"

import axios from "axios";
import * as React from 'react';
import { User } from "@prisma/client";
import { useEffect, useState } from "react";
import { useSession } from "next-auth/react";
import { usePathname } from 'next/navigation'
import { cn } from "@/lib/utils";

const UserProfile = () => {
  const { data: session, status } = useSession();
    const [previousUsername, setPreviousUsername] = useState<string>()
    const [user, setUser] = useState<User>()
    const [loading, setLoading] = useState<boolean>(true)
    const pathname = usePathname()

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

      setPreviousUsername(session.user?.name as string)
      if (session.user) {
        const fetchData = async () => {
          var userData: User = (await axios.get("/api/account")).data
          setUser(userData)
          setLoading(false)
        }

        fetchData().catch(console.error)

        // TODO: check cookies if impersonation is in use.
      }
  }, [session])

  return ( 
    <div className={cn("px-10 py-6 rounded-md bg-blue-300 overflow-hidden wrap", loading && "hidden")}>
      <p className="text-xs text-gray-400">Logged in as:</p>
      <p>{user?.username}</p>
    </div>
   );
}
 
export default UserProfile;