import { useEffect, useState } from "react"
import { NavLink, useNavigate } from "react-router-dom"
import { logout } from "@/api/auth"
import { AUTH_EVENT, isAuthed } from "@/api/token"

export default function ProfileOrLogin() {
  const [authed, setAuthed] = useState(isAuthed)
  const navigate = useNavigate()

  useEffect(() => {
    const update = () => setAuthed(isAuthed())
    window.addEventListener("focus", update)
    window.addEventListener(AUTH_EVENT, update)
    return () => {
      window.removeEventListener("focus", update)
      window.removeEventListener(AUTH_EVENT, update)
    }
  }, [])

  const handleLogout = async () => {
    await logout()
  }

  if (authed) {
    return (
      <div className="flex items-center gap-2">
        <button
          onClick={() => navigate("/admin")}
          className="w-24 h-12 flex items-center justify-center lg:text-lg text-slate-700 hover:text-blue-500 transition-colors"
        >
          <span>个人中心</span>
        </button>
        <button
          onClick={handleLogout}
          className={[
            "w-20 lg:w-24 h-10 lg:h-12 bg-linear-to-r rounded-full flex items-center justify-center lg:text-lg text-white",
            "transition-colors duration-200 ease-in-out",
            "from-blue-500 to-cyan-400 hover:from-blue-500 hover:to-cyan-300",
          ].join(" ")}
        >
          <span>退出登录</span>
        </button>
      </div>
    )
  }

  return (
    <div className="flex items-center">
      <NavLink
        to="/login"
        state={{ tab: "login" }}
        className="w-24 h-12 flex items-center justify-center lg:text-lg"
      >
        <span>登录</span>
      </NavLink>
      <NavLink
        to="/login"
        state={{ tab: "register" }}
        className={[
          "w-20 lg:w-24 h-10 lg:h-12 bg-linear-to-r rounded-full flex items-center justify-center lg:text-lg text-white",
          "transition-colors duration-200 ease-in-out",
          "from-blue-500 to-cyan-400 hover:from-blue-500 hover:to-cyan-300",
        ].join(" ")}
      >
        <span>注册</span>
      </NavLink>
    </div>
  )
}
