'use client';

import { useEffect, useRef } from 'react';
import { socket } from '@/lib/socket';

interface UseSocketProps {
  conversationId: string | null;
  onNewMessage: (message: any) => void;
  onUserTyping: (data: { userId: string; isTyping: boolean; conversationId: string }) => void;
}

export function useSocket({ conversationId, onNewMessage, onUserTyping }: UseSocketProps) {
  const typingTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const connectionAttemptRef = useRef(0);

  useEffect(() => {
    if (!conversationId) {
      return;
    }

    // Connexion au socket si pas connecté avec retry
    const connectSocket = () => {
      if (!socket.connected) {
        try {
          socket.connect();
          connectionAttemptRef.current = 0;
        } catch (error) {
          console.error('Error connecting to Socket.IO:', error);
          // Retry automatique
          if (connectionAttemptRef.current < 3) {
            connectionAttemptRef.current++;
            setTimeout(connectSocket, 2000 * connectionAttemptRef.current);
          }
        }
      }
    };

    connectSocket();

    // Écouter les erreurs de connexion
    const handleConnectError = () => {
      console.warn('Socket.IO connection error');
    };

    const handleDisconnect = () => {
      console.warn('Socket.IO disconnected');
      // Tentative de reconnexion automatique
      if (connectionAttemptRef.current < 3) {
        connectionAttemptRef.current++;
        setTimeout(connectSocket, 2000 * connectionAttemptRef.current);
      }
    };

    socket.on('connect_error', handleConnectError);
    socket.on('disconnect', handleDisconnect);

    // Attendre la connexion avant d'émettre
    const handleConnect = () => {
      if (conversationId) {
        socket.emit('join-conversation', conversationId);
      }
    };

    if (socket.connected) {
      socket.emit('join-conversation', conversationId);
    } else {
      socket.once('connect', handleConnect);
    }

    // Écouter les nouveaux messages
    socket.on('new-message', onNewMessage);

    // Écouter les typing indicators
    socket.on('user-typing', onUserTyping);

    // Nettoyage
    return () => {
      if (socket.connected && conversationId) {
        socket.emit('leave-conversation', conversationId);
      }
      socket.off('new-message', onNewMessage);
      socket.off('user-typing', onUserTyping);
      socket.off('connect_error', handleConnectError);
      socket.off('disconnect', handleDisconnect);
      socket.off('connect', handleConnect);
    };
  }, [conversationId, onNewMessage, onUserTyping]);

  // Fonction pour gérer les typing indicators
  // userId doit être l'UUID Supabase de l'utilisateur
  const handleTyping = (userId: string, isTyping: boolean) => {
    if (!conversationId || !userId) {
      return;
    }

    if (isTyping) {
      socket.emit('conversation-typing-start', { userId, conversationId });
      
      // Arrêter le typing après 3 secondes d'inactivité automatiquement
      if (typingTimeoutRef.current) {
        clearTimeout(typingTimeoutRef.current);
      }
      typingTimeoutRef.current = setTimeout(() => {
        socket.emit('conversation-typing-stop', { userId, conversationId });
      }, 3000);
    } else {
      socket.emit('conversation-typing-stop', { userId, conversationId });
      if (typingTimeoutRef.current) {
        clearTimeout(typingTimeoutRef.current);
        typingTimeoutRef.current = null;
      }
    }
  };

  return {
    handleTyping
  };
}
