import { useCallback } from "react";
import { useAppScope } from "@/app/app-scope/AppScopeProvider.jsx";
import { useTimeZone } from "@/app/timezone/TimeZoneProvider.jsx";
import { getDashboardUserProfileOverview } from "@/features/dashboard/api";
import { useAdminQuery } from "@/shared/hooks/useAdminQuery.js";
import { nextDayStartMillis, startOfDayMillis } from "@/shared/utils/time.js";

const DAY_ROLLOVER_DELAY_MS = 1000;

export function useDashboardPage() {
  const { appCode } = useAppScope();
  const { timeZone } = useTimeZone();

  const queryFn = useCallback(() => {
    // 每次实际请求时重新取 now，确保跨过零点后的手动刷新不会继续沿用前一天的统计区间。
    const endMs = Date.now();
    const startMs = startOfDayMillis(endMs, timeZone);
    if (startMs === null) {
      // 无法计算边界时直接失败，避免用错误日期请求并把跨天数据伪装成“当天”。
      throw new Error("无法计算当天统计时间范围");
    }
    return getDashboardUserProfileOverview({ appCode, endMs, startMs, statTz: timeZone });
  }, [appCode, timeZone]);

  const { data, error, loading, reload } = useAdminQuery(queryFn, {
    errorMessage: "加载用户画像失败",
    initialData: null,
    // App 与时区都会改变统计口径，必须隔离缓存，避免切换时短暂展示上一口径的数据。
    queryKey: ["dashboard", "user-profile-overview", appCode, timeZone],
    // 页面可能整夜保持打开；在所选显示时区跨过零点后主动重取，确保“当天新增/当前日活”不会停留在前一天。
    refetchInterval: () => dashboardDayRolloverInterval(timeZone)
  });

  return {
    error,
    loading,
    overview: data,
    reload
  };
}

export function dashboardDayRolloverInterval(timeZone, now = Date.now()) {
  const nextStartMs = nextDayStartMillis(now, timeZone);
  if (nextStartMs === null) {
    return false;
  }
  return Math.max(DAY_ROLLOVER_DELAY_MS, nextStartMs - now + DAY_ROLLOVER_DELAY_MS);
}
