import { useState } from 'react';
import * as Location from 'expo-location';


export const useLocation = () => {
  const [errorMsg, setErrorMsg] = useState<string | null>(null);
  const [latitude, setLatitude] = useState<number | null>(null);
  const [longitude, setLongitude] = useState<number | null>(null);
  const [loading, setLoading] = useState(false);


  const geocodeAddress = async (address: string) => {
    try {
      setLoading(true);
      setErrorMsg(null);

      const { status } = await Location.requestForegroundPermissionsAsync();

      if (status !== 'granted') {
        throw new Error('Permission localisation refusée');
      }
      const result = await Location.geocodeAsync(address);

      if (!result || result.length === 0) {
        throw new Error("Adresse introuvable");
      }

      const { latitude, longitude } = result[0];

      setLatitude(latitude);
      setLongitude(longitude);

      return { latitude, longitude };
    } catch (error: any) {
      console.error(error);
      setErrorMsg("Impossible de localiser cette adresse");
      return null;
    } finally {
      setLoading(false);
    }
  };

  return {
    latitude,
    longitude,
    errorMsg,
    loading,
    geocodeAddress,
  };
};
