"use Client";

import React, { useState, useEffect } from "react";
import { checkAuth, signOut } from "@/utils/auth";
import { getCookie } from "cookies-next";
import { useRouter } from "next/navigation";

export default function AuthBar({ onNotLoginedClick = () => {} }) {
  const router = useRouter();
  const [isLogined, setIsLogined] = useState();
  const [cookies, setCookies] = useState();
  const [showDetail, setShowDetail] = useState(false);

  useEffect(() => {
    const prepare = async () => {
      const tempIsLogined = await checkAuth();
      const accountCookie = getCookie("account");
      const account =
        accountCookie == undefined ? {} : JSON.parse(accountCookie);
      setIsLogined(tempIsLogined);
      setCookies(account);
    };
    prepare();
  }, []);

  //退出登录
  const handleSignOut = () => {
    signOut();
    window.location.reload();
  };

  //点击登录
  const handleSignIn = () => {
    onNotLoginedClick();
    router.push("/auth/login/phonenumlogin");
  };

  //点击已购
  const handlePurchased = () => {
    router.push("/purchased");
  };

  return (
    <div className="flex flex-row absolute right-4 top-4">
      {isLogined ? (
        <div className="flex flex-col items-end">
          <div
            onClick={() => setShowDetail(!showDetail)}
            className="flex flex-col cursor-pointer bg-[#FFFFFF1A] rounded-full px-4 py-2"
          >
            <p className="text-white text-base font-medium">{cookies?.name}</p>
          </div>
          <div
            className={`flex flex-col items-center transition-max-height ease-in-out duration-300 overflow-hidden max-h-0 ${
              showDetail ? "max-h-32" : ""
            }`}
          >
            <div
              onClick={handlePurchased}
              className="flex flex-row cursor-pointer items-center justify-center p-2"
            >
              <p className="text-white text-base font-medium ml-2">已购</p>
            </div>
            <div className="bg-[#FFFFFF26] h-0.5 w-4/5"></div>
            <div
              onClick={handleSignOut}
              className="flex flex-row cursor-pointer items-center justify-center p-2"
            >
              <p className="text-white text-base font-medium ml-2">登出</p>
            </div>
          </div>
        </div>
      ) : (
        <div
          onClick={handleSignIn}
          className="flex cursor-pointer bg-[#FFFFFF1A] rounded-full px-4 py-2"
        >
          <p className="text-white text-base font-medium">点击登录</p>
        </div>
      )}
    </div>
  );
}
