import { useEffect, useCallback } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { signalRService } from '../services/signalRService';
import { PublishingProgressUpdate, BuildStatusUpdate } from '../types';

export const useSignalR = () => {
  const queryClient = useQueryClient();

  useEffect(() => {
    const startConnection = async () => {
      try {
        await signalRService.start();
      } catch (error) {
        console.error('Failed to start SignalR connection:', error);
      }
    };

    startConnection();

    return () => {
      signalRService.stop();
    };
  }, []);

  const subscribeToPublishingProgress = useCallback(
    (callback: (update: PublishingProgressUpdate) => void) => {
      return signalRService.subscribe<PublishingProgressUpdate>('PublishingProgress', callback);
    },
    []
  );

  const subscribeToBuildStatusUpdates = useCallback(
    (callback: (update: BuildStatusUpdate) => void) => {
      return signalRService.subscribe<BuildStatusUpdate>('BuildStatusUpdate', (update) => {
        // Invalidate related queries when build status changes
        queryClient.invalidateQueries({ queryKey: ['project-status'] });
        queryClient.invalidateQueries({ queryKey: ['project-builds'] });
        callback(update);
      });
    },
    [queryClient]
  );

  const subscribeToPublicationCompleted = useCallback(
    (callback: (publicationId: number) => void) => {
      return signalRService.subscribe<number>('PublicationCompleted', (publicationId) => {
        // Invalidate publication-related queries
        queryClient.invalidateQueries({ queryKey: ['publications'] });
        queryClient.invalidateQueries({ queryKey: ['active-publications'] });
        queryClient.invalidateQueries({ queryKey: ['publication', publicationId] });
        callback(publicationId);
      });
    },
    [queryClient]
  );

  const subscribeToPublicationFailed = useCallback(
    (callback: (data: { publicationId: number; error: string }) => void) => {
      return signalRService.subscribe<{ publicationId: number; error: string }>('PublicationFailed', (data) => {
        // Invalidate publication-related queries
        queryClient.invalidateQueries({ queryKey: ['publications'] });
        queryClient.invalidateQueries({ queryKey: ['active-publications'] });
        queryClient.invalidateQueries({ queryKey: ['publication', data.publicationId] });
        callback(data);
      });
    },
    [queryClient]
  );

  const joinPublicationGroup = useCallback(async (publicationId: number) => {
    await signalRService.joinPublicationGroup(publicationId);
  }, []);

  const leavePublicationGroup = useCallback(async (publicationId: number) => {
    await signalRService.leavePublicationGroup(publicationId);
  }, []);

  return {
    isConnected: signalRService.isConnected,
    connectionState: signalRService.connectionState,
    subscribeToPublishingProgress,
    subscribeToBuildStatusUpdates,
    subscribeToPublicationCompleted,
    subscribeToPublicationFailed,
    joinPublicationGroup,
    leavePublicationGroup,
  };
};