import { useCallback, useEffect, useRef, useState } from "react";
import { HttpError } from "../../shared/api/errors";
import type { PageResult } from "../../shared/api/types";
import { documentApi } from "./documentApi";
import type {
  DocumentDetail,
  DocumentListQuery,
  DocumentSummary,
  SubPlanListQuery,
} from "./documentTypes";
import { useContentRevision } from "../../shared/state/contentRefresh";

export interface RemotePageState<T> {
  data: PageResult<T> | null;
  loading: boolean;
  error: HttpError | null;
  retry: () => void;
}

const initialPageState = <T,>(): RemotePageState<T> => ({
  data: null,
  loading: true,
  error: null,
  retry: () => undefined,
});

function useDebouncedPage<T>(
  load: (signal: AbortSignal) => Promise<PageResult<T>>,
  dependencies: readonly unknown[],
  debounceKey: string | undefined,
  enabled = true,
  debounceMs = 300,
): RemotePageState<T> {
  const [state, setState] = useState<RemotePageState<T>>(initialPageState);
  const requestVersion = useRef(0);
  const previousDebounceKey = useRef(debounceKey);
  const [retryVersion, setRetryVersion] = useState(0);
  const retry = useCallback(() => setRetryVersion((value) => value + 1), []);

  useEffect(() => {
    if (!enabled) {
      setState((current) => ({ ...current, loading: false, error: null, retry }));
      return;
    }
    const version = ++requestVersion.current;
    const controller = new AbortController();
    const delay = previousDebounceKey.current === debounceKey ? 0 : debounceMs;
    previousDebounceKey.current = debounceKey;
    const timer = window.setTimeout(() => {
      setState((current) => ({ ...current, loading: true, error: null, retry }));
      void load(controller.signal)
        .then((data) => {
          if (version === requestVersion.current) {
            setState({ data, loading: false, error: null, retry });
          }
        })
        .catch((error: unknown) => {
          if (
            version !== requestVersion.current ||
            controller.signal.aborted
          ) {
            return;
          }
          setState({
            data: null,
            loading: false,
            retry,
            error:
              error instanceof HttpError
                ? error
                : new HttpError({
                    httpStatus: 0,
                    code: "INTERNAL_ERROR",
                    message: "请求失败",
                    details: null,
                    requestId: "unknown",
                    cause: error,
                  }),
          });
        });
    }, delay);

    return () => {
      window.clearTimeout(timer);
      controller.abort();
    };
    // The caller passes the complete primitive dependency set. Retry and
    // enabled are appended here so errors can be retried without mutating filters.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [...dependencies, enabled, retryVersion]);

  return { ...state, retry };
}

export function useDocumentList(
  query: DocumentListQuery,
  enabled = true,
): RemotePageState<DocumentSummary> {
  const revision = useContentRevision("documents");
  return useDebouncedPage(
    (signal) => documentApi.list(query, signal),
    [
      query.documentType,
      query.categoryId,
      query.keyword,
      query.securityLevel,
      query.visibilityType,
      query.status,
      query.updatedFrom,
      query.updatedTo,
      query.sortBy,
      query.sortDirection,
      query.page,
      query.pageSize,
      revision,
    ],
    query.keyword,
    enabled,
  );
}

export function useSubPlanList(
  mainPlanId: string | null,
  query: SubPlanListQuery,
  enabled = true,
): RemotePageState<DocumentSummary> {
  const revision = useContentRevision("documents");
  return useDebouncedPage(
    (signal) =>
      mainPlanId
        ? documentApi.subPlans(mainPlanId, query, signal)
        : Promise.resolve({
            items: [],
            page: query.page ?? 1,
            pageSize: query.pageSize ?? 20,
            total: 0,
            totalPages: 0,
          }),
    [
      mainPlanId,
      query.keyword,
      query.status,
      query.updatedFrom,
      query.updatedTo,
      query.sortBy,
      query.sortDirection,
      query.page,
      query.pageSize,
      revision,
    ],
    query.keyword,
    enabled,
  );
}

type DetailLoader = (id: string, signal?: AbortSignal) => Promise<DocumentDetail>;
const detailCache = new Map<string, DocumentDetail>();
const detailRequests = new Map<string, Promise<DocumentDetail>>();

export function loadDetailOnce(
  scope: "document" | "attachment",
  id: string,
  loader: DetailLoader,
): Promise<DocumentDetail> {
  const key = `${scope}:${id}`;
  const cached = detailCache.get(key);
  if (cached) return Promise.resolve(cached);
  const pending = detailRequests.get(key);
  if (pending) return pending;

  const request = loader(id)
    .then((detail) => {
      detailCache.set(key, detail);
      return detail;
    })
    .finally(() => {
      detailRequests.delete(key);
    });
  detailRequests.set(key, request);
  return request;
}

export function clearDetailCacheForTests(): void {
  detailCache.clear();
  detailRequests.clear();
}

export function invalidateDetail(scope: "document" | "attachment", id: string): void {
  detailCache.delete(`${scope}:${id}`);
  detailRequests.delete(`${scope}:${id}`);
}

export function cacheDetail(
  scope: "document" | "attachment",
  detail: DocumentDetail,
): void {
  detailCache.set(`${scope}:${detail.id}`, detail);
}
