import * as Location from 'expo-location';

export const calculateDistance = async (
    stationLat: number,
    stationLng: number,
    currentLocation?: Location.LocationObject
): Promise<number | null> => {
    try {
        if (!currentLocation) {
            let { status } = await Location.requestForegroundPermissionsAsync();
            if (status !== 'granted') {
                throw new Error('Permission to access location was denied');
            }
            currentLocation = await Location.getLastKnownPositionAsync({});
        }

        const { latitude: lat1, longitude: lon1 } = currentLocation.coords;
        const lat2 = stationLat;
        const lon2 = stationLng;

        const R = 6371e3; // Earth's radius in meters
        const φ1 = (lat1 * Math.PI) / 180;
        const φ2 = (lat2 * Math.PI) / 180;
        const Δφ = ((lat2 - lat1) * Math.PI) / 180;
        const Δλ = ((lon2 - lon1) * Math.PI) / 180;

        const a =
            Math.sin(Δφ / 2) * Math.sin(Δφ / 2) + Math.cos(φ1) * Math.cos(φ2) * Math.sin(Δλ / 2) * Math.sin(Δλ / 2);
        const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

        return R * c; // Distance in meters
    } catch (error) {
        console.error('Error calculating distance:', error);
        return null;
    }
};
