import { useCallback, useMemo, useState } from "react";
import { useAdminQuery } from "@/shared/hooks/useAdminQuery.js";
import { getDashboardOverview } from "@/features/dashboard/api";

const emptyData = { overview: null };

export function useDashboardPage() {
  const [range, setRange] = useState("近 1 小时");

  const queryFn = useCallback(async () => {
    const overview = await getDashboardOverview();
    return { overview };
  }, []);

  const { data, error, loading, reload } = useAdminQuery(queryFn, {
    errorMessage: "加载总览失败",
    initialData: emptyData,
    keepPreviousData: true,
    queryKey: ["dashboard", "overview"]
  });

  const overview = data?.overview;

  const stats = useMemo(() => {
    if (!overview) {
      return { activeUsers: 0, disabledUsers: 0, lockedUsers: 0, logsToday: 0, menuTotal: 0, rolesTotal: 0, usersTotal: 0 };
    }
    return {
      activeUsers: overview.activeUsers,
      disabledUsers: overview.disabledUsers,
      lockedUsers: overview.lockedUsers,
      logsToday: overview.logsToday,
      menuTotal: overview.menuTotal,
      rolesTotal: overview.rolesTotal,
      usersTotal: overview.usersTotal
    };
  }, [overview]);

  return {
    error,
    loading,
    overview,
    range,
    reload,
    setRange,
    stats
  };
}
