import { useCallback } from "react";
import Taro from "@tarojs/taro";
import { apiRequest } from "../api/client";
import { useUserStore } from "../store/user";
import { currentPageUrl } from "./onboarding";

function isMemberStatus(status: unknown) {
  const s = String(status || "").toLowerCase();
  return s === "active";
}

function hasMemberRole(roles: unknown) {
  if (!Array.isArray(roles)) return false;
  return roles.some((r: unknown) => String(r).replace(/^ROLE_/, "").toUpperCase() === "MEMBER");
}

function hasManageRole(roles: unknown) {
  if (!Array.isArray(roles)) return false;
  return roles.some((r: unknown) => ["BRANCH_ADMIN", "CITY_ADMIN", "PLATFORM_ADMIN"].includes(String(r)));
}

export async function ensureMeLoaded() {
  const current = useUserStore.getState().me;
  if (current) return current;
  const me = await apiRequest("/api/me");
  useUserStore.setState({ me });
  return me;
}

export async function ensureMemberAccess(message = "需成为会员后才能使用该功能") {
  let me: any;
  try {
    me = await ensureMeLoaded();
  } catch (err: any) {
    if (String(err?.message || "").includes("UNAUTHORIZED")) {
      Taro.showToast({ title: "请先登录", icon: "none" });
      redirectToLogin();
      return false;
    }
    Taro.showToast({ title: err?.message || "暂时无法校验身份", icon: "none" });
    return false;
  }
  if (isMemberStatus(me?.memberStatus) || hasMemberRole(me?.roles) || hasManageRole(me?.roles)) {
    return true;
  }
  Taro.showToast({ title: message, icon: "none" });
  setTimeout(() => Taro.navigateTo({ url: "/pages/join/index" }), 700);
  return false;
}

/** React hook for permission checks — avoids repeated ensureMeLoaded calls */
export function usePermission() {
  const check = useCallback(async (message?: string) => {
    return ensureMemberAccess(message);
  }, []);

  const isAdmin = useCallback(async () => {
    const me = await ensureMeLoaded();
    return hasManageRole(me?.roles);
  }, []);

  const isMember = useCallback(async () => {
    const me = await ensureMeLoaded();
    return isMemberStatus(me?.memberStatus) || hasMemberRole(me?.roles) || hasManageRole(me?.roles);
  }, []);

  return { check, isAdmin, isMember };
}

function redirectToLogin() {
  const redirect = currentPageUrl();
  setTimeout(() => Taro.reLaunch({ url: redirect ? `/pages/login/index?redirect=${encodeURIComponent(redirect)}` : "/pages/login/index" }), 500);
}
