import { useEffect, useState } from 'react';

import type { NetworkSnapshot } from '../services/api';
import { ApiError, fetchNetworkSnapshot } from '../services/api';
import { useAuth } from '../state/AuthContext';

interface NetworkSnapshotState {
  readonly data: NetworkSnapshot | null;
  readonly status: 'idle' | 'loading' | 'success' | 'error';
  readonly error: string | null;
}

const INITIAL_STATE: NetworkSnapshotState = {
  data: null,
  status: 'idle',
  error: null,
};

export function useNetworkSnapshot(token: string | null): NetworkSnapshotState {
  const [state, setState] = useState<NetworkSnapshotState>(INITIAL_STATE);
  const { logout } = useAuth();

  useEffect(() => {
    const abortController = new AbortController();

    if (!token) {
      setState(INITIAL_STATE);
      return () => abortController.abort();
    }

    const authToken = token;

    async function load() {
      setState({ data: null, status: 'loading', error: null });
      try {
        const snapshot = await fetchNetworkSnapshot(authToken, abortController.signal);
        setState({ data: snapshot, status: 'success', error: null });
      } catch (error) {
        if (abortController.signal.aborted) {
          return;
        }
        if (error instanceof ApiError && error.status === 401) {
          logout(error.message);
          setState({ data: null, status: 'error', error: error.message });
          return;
        }
        setState({ data: null, status: 'error', error: (error as Error).message });
      }
    }

    load();
    return () => abortController.abort();
  }, [token, logout]);

  return state;
}
