// hooks/useTripTracking.ts
'use client';

import { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import io, { Socket } from 'socket.io-client';

type Location = {
    latitude: number;
    longitude: number;
};

export function useTripTracking(tripId: any) {
    const [location, setLocation] = useState<Location | null>(null);
    const [socket, setSocket] = useState<Socket | null>(null);

    const auth = useSelector((state: any) => state.auth);

    useEffect(() => {
        if (!tripId) return;

        const newSocket = io(process.env.NEXT_PUBLIC_API_SOCKET_URL, {
            auth: { token: auth?.token },
            transports: ['websocket'],
        });

        setSocket(newSocket);

        newSocket.on('connect', () => {
            console.log('Socket connected:', newSocket.id);

            // Join trip room
            newSocket.emit('joinTrip', tripId);

            // Get latest location
            newSocket.emit('getLatestLocation', tripId, (res: any) => {
                if (res?.latest) {
                    setLocation({
                        latitude: Number(res.latest.latitude),
                        longitude: Number(res.latest.longitude),
                    });
                }
            });
        });

        newSocket.on('locationUpdate', (data: Location | null) => {
            if (data?.latitude != null && data?.longitude != null) {
                setLocation({
                    latitude: Number(data.latitude),
                    longitude: Number(data.longitude),
                });
            } else {
                console.warn('Received invalid location data:', data);
            }
        });

        return () => {
            newSocket.disconnect();
        };
    }, [tripId]);

    return { location, socket };
}
