import { useEffect, useReducer, useRef, useState } from "react";
import { loadChangedFiles, loadFileDiff } from "./changes-api.js";
import { initialChangesState, reduceChangesState } from "./changes-state.js";
import { loadPatchDiffs } from "./patch-diffs.js";
export function useChanges(session) {
  const [state, dispatch] = useReducer(reduceChangesState, initialChangesState);
  const [sheetOpen, setSheetOpen] = useState(false);
  const [sheetFiles, setSheetFiles] = useState([]);
  const sessionRef = useRef(session);
  sessionRef.current = session;
  useEffect(() => {
    dispatch({ type: "session.changed" });
    setSheetOpen(false);
    setSheetFiles([]);
    if (session) void refresh();
  }, [session?.id]);
  async function refresh() {
    if (!session) return false;
    const requestSessionId = session.id;
    dispatch({ type: "files.started" });
    try {
      const result = await loadChangedFiles(requestSessionId);
      if (!isCurrentSessionRequest(sessionRef, requestSessionId)) return false;
      dispatch({ type: "files.loaded", files: result.files ?? [], available: result.available !== false });
      return true;
    } catch {
      if (!isCurrentSessionRequest(sessionRef, requestSessionId)) return false;
      dispatch({ type: "files.failed" });
      return false;
    }
  }
  async function open(files) {
    if (!session) return false;
    const requestSessionId = session.id;
    setSheetFiles(files);
    setSheetOpen(true);
    dispatch({ type: "diffs.started" });
    const diffs = await loadPatchDiffs(files,
      (path) => loadFileDiff(requestSessionId, path),
      (diff) => {
        if (isCurrentSessionRequest(sessionRef, requestSessionId)) {
          dispatch({ type: "diffs.itemLoaded", diff });
        }
      }
    );
    if (!isCurrentSessionRequest(sessionRef, requestSessionId)) return false;
    dispatch({ type: "diffs.loaded", diffs });
    return true;
  }
  return { ...state, refresh, open, sheetOpen, sheetFiles, closeSheet: () => setSheetOpen(false), acceptFiles: (files) => dispatch({ type: "files.pushed", files }) };
}

function isCurrentSessionRequest(sessionRef, requestSessionId) {
  return Boolean(requestSessionId && sessionRef.current?.id === requestSessionId);
}
