import { View, Text } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { useEffect } from "react";
import { isLoggedInAsAdmin } from "../../utils/adminAuth";
import { useUserStore } from "../../store/user";

interface AdminGuardProps {
  children: React.ReactNode;
}

export default function AdminGuard({ children }: AdminGuardProps) {
  const adminUser = useUserStore((s) => s.adminUser);
  const adminLoading = useUserStore((s) => s.loading);
  const adminError = useUserStore((s) => s.error);
  const bootstrapAdmin = useUserStore((s) => s.bootstrapAdmin);

  useEffect(() => {
    if (!isLoggedInAsAdmin()) {
      Taro.redirectTo({ url: "/pages/login/index?staff=1" });
      return;
    }
    if (!adminUser && !adminLoading && !adminError) {
      void bootstrapAdmin();
    }
  }, [adminError, adminLoading, adminUser, bootstrapAdmin]);

  useEffect(() => {
    if (!adminUser && !adminLoading && adminError) {
      Taro.showToast({ title: "请重新登录管理员账号", icon: "none" });
      Taro.redirectTo({ url: "/pages/login/index?staff=1" });
    }
  }, [adminError, adminLoading, adminUser]);

  if (!adminUser) {
    return (
      <View className="admin-guard-loading">
        <Text>{adminLoading ? "加载中..." : "正在校验管理员身份..."}</Text>
      </View>
    );
  }

  return <>{children}</>;
}
