import { useEffect, useState } from 'react';
import { chatConnectionGateway } from '../data/chatConnectionGateway';
import { chatGateway } from '../data/chatGateway';
import type { ChatRuntimeJobDetail, ChatRuntimeSnapshot } from '../../mainChatPanel/types';

type UseRuntimeDataOptions = {
  activeSessionId: string;
  isDeferringAuxiliaryChatRequests: boolean;
};

export function useRuntimeData({
  activeSessionId,
  isDeferringAuxiliaryChatRequests,
}: UseRuntimeDataOptions) {
  const [runtimeSnapshot, setRuntimeSnapshot] = useState<ChatRuntimeSnapshot | null>(null);
  const [runtimeJobDetail, setRuntimeJobDetail] = useState<ChatRuntimeJobDetail | null>(null);

  useEffect(() => {
    let isCancelled = false;

    const loadRuntimeSnapshot = async () => {
      try {
        const snapshot = await chatGateway.fetchRuntimeSnapshot();

        if (!isCancelled) {
          setRuntimeSnapshot(snapshot);
          chatConnectionGateway.setSharedRuntimeSnapshot(snapshot);
        }
      } catch {
        if (!isCancelled) {
          setRuntimeSnapshot(null);
          chatConnectionGateway.setSharedRuntimeSnapshot(null);
        }
      }
    };

    void loadRuntimeSnapshot();

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

  useEffect(() => {
    if (!activeSessionId.trim()) {
      return;
    }

    if (isDeferringAuxiliaryChatRequests) {
      return;
    }

    let isCancelled = false;

    const syncRuntimeSnapshotForActiveSession = async () => {
      try {
        const snapshot = await chatGateway.fetchRuntimeSnapshot();

        if (!isCancelled) {
          setRuntimeSnapshot(snapshot);
          chatConnectionGateway.setSharedRuntimeSnapshot(snapshot);
        }
      } catch {
        if (!isCancelled) {
          setRuntimeSnapshot(null);
          chatConnectionGateway.setSharedRuntimeSnapshot(null);
        }
      }
    };

    void syncRuntimeSnapshotForActiveSession();

    return () => {
      isCancelled = true;
    };
  }, [activeSessionId, isDeferringAuxiliaryChatRequests]);

  const handleRuntimeEvent = (snapshot: ChatRuntimeSnapshot) => {
    setRuntimeSnapshot(snapshot);
    chatConnectionGateway.setSharedRuntimeSnapshot(snapshot);
  };

  const handleRuntimeDetailEvent = (detail: ChatRuntimeJobDetail) => {
    setRuntimeJobDetail(detail);
  };

  return {
    runtimeSnapshot,
    runtimeJobDetail,
    setRuntimeSnapshot,
    handleRuntimeEvent,
    handleRuntimeDetailEvent,
  };
}
