import { useCallback, useEffect, useRef, useState } from "react";
import { HttpError } from "../../shared/api/errors";
import { useContentRevision } from "../../shared/state/contentRefresh";
import { statisticsApi, type StatisticsApi } from "./statisticsApi";
import type { DocumentStatistics } from "./statisticsTypes";

export function useDocumentStatistics(
  api: StatisticsApi = statisticsApi,
) {
  const [data, setData] = useState<DocumentStatistics | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<HttpError | null>(null);
  const [revision, setRevision] = useState(0);
  const requestVersion = useRef(0);
  const documentRevision = useContentRevision("documents");
  const attachmentRevision = useContentRevision("attachments");
  const refresh = useCallback(() => setRevision((value) => value + 1), []);

  useEffect(() => {
    const version = ++requestVersion.current;
    const controller = new AbortController();
    const timer = window.setTimeout(() => {
      setLoading(true);
      setError(null);
      void api
        .documents(controller.signal)
        .then((next) => {
          if (
            !controller.signal.aborted &&
            version === requestVersion.current
          ) {
            setData(next);
            setLoading(false);
          }
        })
        .catch((value: unknown) => {
          if (
            controller.signal.aborted ||
            version !== requestVersion.current
          ) {
            return;
          }
          setData(null);
          setLoading(false);
          setError(
            value instanceof HttpError
              ? value
              : new HttpError({
                  httpStatus: 0,
                  code: "INTERNAL_ERROR",
                  message: "文档统计加载失败",
                  details: null,
                  requestId: "client",
                  cause: value,
                }),
          );
        });
    }, 0);
    return () => {
      window.clearTimeout(timer);
      controller.abort();
    };
  }, [
    api,
    attachmentRevision,
    documentRevision,
    revision,
  ]);

  return { data, loading, error, refresh };
}

