import React, { useMemo } from "react";
import { useQuery } from "@apollo/client";

import {
  GET_CORPUS_DOCUMENT_GRAPH,
  GetCorpusDocumentGraphInputType,
  GetCorpusDocumentGraphOutputType,
  CorpusDocumentGraphNode,
  CorpusDocumentGraphEdge,
} from "../../../../graphql/queries";
import { DocumentGraphGlimpse } from "./DocumentGraphGlimpse";

// Stable empty-array references. ``graph?.nodes ?? []`` would mint a fresh ``[]``
// on every render while the query is in flight, defeating DocumentGraphGlimpse's
// ``useMemo([nodes])`` / ``useMemo([nodes, edges])`` (the layout would recompute
// on every render until data arrives). Module-level constants are referentially
// stable, so the memos stay cached.
const EMPTY_NODES: CorpusDocumentGraphNode[] = [];
const EMPTY_EDGES: CorpusDocumentGraphEdge[] = [];

/**
 * DocumentGraphLive — fetches the corpus document-relationship graph and feeds
 * the presentational ``DocumentGraphGlimpse``. Shared by the composed
 * ``CorpusIntelligenceOverview`` (landing fallback) and the ``document-graph``
 * CAML embed so the query wiring lives in one place.
 */
interface DocumentGraphLiveProps {
  corpusId: string;
  onExplore?: () => void;
  /** Render nothing (rather than the empty card) when there are no edges —
   * used by the CAML-article embed so a relationship-free corpus home stays
   * clean. See DocumentGraphGlimpse.hideWhenEmpty. */
  hideWhenEmpty?: boolean;
  testId?: string;
}

export const DocumentGraphLive: React.FC<DocumentGraphLiveProps> = ({
  corpusId,
  onExplore,
  hideWhenEmpty = false,
  testId,
}) => {
  const variables = useMemo(() => ({ corpusId }), [corpusId]);

  const { data, loading, error } = useQuery<
    GetCorpusDocumentGraphOutputType,
    GetCorpusDocumentGraphInputType
  >(GET_CORPUS_DOCUMENT_GRAPH, { variables });

  const graph = data?.corpusDocumentGraph;

  return (
    <DocumentGraphGlimpse
      nodes={graph?.nodes ?? EMPTY_NODES}
      edges={graph?.edges ?? EMPTY_EDGES}
      totalNodeCount={graph?.totalNodeCount ?? 0}
      totalEdgeCount={graph?.totalEdgeCount ?? 0}
      truncated={graph?.truncated ?? false}
      loading={loading && !graph}
      error={!!error && !graph}
      hideWhenEmpty={hideWhenEmpty}
      onExplore={onExplore}
      testId={testId}
    />
  );
};
