"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import ThemeMode from "@/components/ThemeMode";
import { useGlobalContext } from "@/providers/GlobalProvider";
import { getUserSession } from "@/utils/user";
import { getUserInfo } from "@/api/client";

export default function Header({ name }: { name: string }) {
  const router = useRouter();
  const { loginShow, changeLoginShow,uploadUserInfoState } = useGlobalContext();
  const [isLogin, setIsLogin] = useState(false);
  const [nickName, setNickName] = useState("");

  const Login = () => {
    changeLoginShow(true);
  };

  useEffect(() => {
    if (getUserSession()) {
      getUserInfo().then((data) => {
        if (data.code === 0) {
          setIsLogin(true);
          setNickName(data.data.nickname);
        }
      });
    }
  }, [loginShow,uploadUserInfoState]);

  return (
    <header className="sticky w-full flex gap-4 justify-between items-center top-0 shadow dark:shadow-none backdrop-blur dark:bg-transparent transition-all py-2 px-1 z-50">
      <div className="flex gap-3 justify-between items-center grow-0 shrink-0">
        <img src="/logo.png" alt="logo" width={40} height={40} />
        <div className="hidden md:block">
          <h1 className="global-txt-color text-xl">{name}</h1>
        </div>
      </div>
      <div className="absolute top-2/4 left-1/2 -translate-x-1/2 -translate-y-2/4 max-md:hidden"></div>
      <div className="flex justify-between items-center grow-0 shrink-0">
        {isLogin && (
          <a
            onClick={() => router.push("/user-center.html")}
            className="cursor-pointer ease-in-out p-2 rounded-md text-gray-700 dark:text-gray-200 hover:text-gray-900 dark:hover:text-white hover:bg-gray-50 dark:hover:bg-gray-800"
          >
            {nickName}
          </a>
        )}
        {!isLogin && (
          <button
            className="inline-flex py-2 px-2 rounded-lg items-center text-white global-bg-color border-0 focus:outline-none mr-3"
            onClick={Login}
          >
            <span className="ml-1 pr-2 flex items-start flex-col leading-none">
              <span className="title-font font-medium">用户登录</span>
            </span>
          </button>
        )}
        <ThemeMode />
      </div>
    </header>
  );
}
