import { startTransition, useEffect, useState } from 'react';
import { researchBridge } from '../lib/researchBridge';
import type {
  GhostReviewAction,
  NoteType,
  ResearchWorkspace,
  ThesisStatus,
  WorkspaceViewKind,
} from '../types/research';

interface UseResearchWorkspaceArgs {
  workspaceId: string | null;
  initialView?: WorkspaceViewKind;
}

export const useResearchWorkspace = ({
  workspaceId,
  initialView = 'canvas',
}: UseResearchWorkspaceArgs) => {
  const [workspace, setWorkspace] = useState<ResearchWorkspace | null>(null);
  const [selectedView, setSelectedView] = useState<WorkspaceViewKind>(initialView);
  const [isLoadingWorkspace, setIsLoadingWorkspace] = useState(false);

  useEffect(() => {
    if (!workspaceId) {
      setWorkspace(null);
      return;
    }

    let cancelled = false;
    setIsLoadingWorkspace(true);
    void researchBridge.getResearchWorkspace(workspaceId).then((nextWorkspace) => {
      if (!cancelled) {
        setWorkspace(nextWorkspace);
        setSelectedView(nextWorkspace.defaultView);
      }
    }).finally(() => {
      if (!cancelled) {
        setIsLoadingWorkspace(false);
      }
    });

    return () => {
      cancelled = true;
    };
  }, [workspaceId]);

  const archiveNote = async (noteId: string, archived: boolean) => {
    return researchBridge.archiveResearchNote({ noteId, archived });
  };

  const updateNote = async (request: Parameters<typeof researchBridge.updateResearchNote>[0]) =>
    researchBridge.updateResearchNote(request);

  const promoteNoteToThesis = async (
    noteId: string,
    thesisStatus?: ThesisStatus,
    noteType?: NoteType,
  ) => researchBridge.promoteNoteToThesis({ noteId, thesisStatus, noteType });

  const reviewGhost = async (ghostNoteId: string, action: GhostReviewAction) =>
    researchBridge.reviewGhostNote({ ghostNoteId, action });

  const setView = (view: WorkspaceViewKind) => {
    startTransition(() => {
      setSelectedView(view);
    });
  };

  return {
    workspace,
    setWorkspace,
    selectedView,
    setView,
    isLoadingWorkspace,
    archiveNote,
    updateNote,
    promoteNoteToThesis,
    reviewGhost,
  };
};
