import { useEffect, useRef, useState } from 'react';
import { io, Socket } from 'socket.io-client';
import { useAuth } from './useAuth';

const SOCKET_URL = 'http://localhost:5000';

export function useSocket() {
  const { token, user } = useAuth();
  const socketRef = useRef<Socket | null>(null);
  const [connected, setConnected] = useState(false);

  useEffect(() => {
    if (!token || !user) return;

    const socket = io(SOCKET_URL, {
      auth: { token },
      transports: ['websocket'],
    });

    socketRef.current = socket;

    socket.on('connect', () => {
      setConnected(true);
      socket.emit('join_company', { company_id: user.company_id });
    });

    socket.on('disconnect', () => {
      setConnected(false);
    });

    return () => {
      socket.disconnect();
      socketRef.current = null;
      setConnected(false);
    };
  }, [token, user]);

  const joinJob = (jobId: number) => {
    socketRef.current?.emit('join_job', { job_id: jobId });
  };

  const onJobCreated = (callback: (data: any) => void) => {
    socketRef.current?.on('job_created', callback);
    return () => socketRef.current?.off('job_created', callback);
  };

  const onJobAssigned = (callback: (data: any) => void) => {
    socketRef.current?.on('job_assigned', callback);
    return () => socketRef.current?.off('job_assigned', callback);
  };

  const onJobStatusChanged = (callback: (data: any) => void) => {
    socketRef.current?.on('job_status_changed', callback);
    return () => socketRef.current?.off('job_status_changed', callback);
  };

  const onLocationUpdate = (callback: (data: any) => void) => {
    socketRef.current?.on('location_update', callback);
    return () => socketRef.current?.off('location_update', callback);
  };

  return {
    socket: socketRef.current,
    connected,
    joinJob,
    onJobCreated,
    onJobAssigned,
    onJobStatusChanged,
    onLocationUpdate,
  };
}
