import { ref } from "vue";
import { decode } from 'polyline';

export default function useDirectionsRender() {

  const mapKey = import.meta.env.VITE_MAP_KEY;

    const originCoords = ref(null);
    const destinationCoords = ref(null);

    // const geocodeAddress = async (address) => {
    //   try {
    //       const response = await fetch(
    //         `https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(
    //           address
    //         )}&key=${mapKey}`
    //       );
    //       const data = await response.json();
    //       const location = data.results[0].geometry.location;
    //       return location;
    //   } catch (error) {
    //     return null;
    //   }
    // };

    const geocodeAddress = async (address) => {
      try {
        const geocoder = new google.maps.Geocoder();
        console.log(address)
        const data = await geocoder.geocode({ address: address });
        const latitude = data.results[0].geometry.location.lat();
        const longitude = data.results[0].geometry.location.lng();
        return {lng: longitude, lat: latitude};
      } catch (error) {
        console.log('Error location', error);
        return null;
      }
    };

    const getDirections = async (originCoords, destinationCoords) => {
      try {
        const directionsService = new google.maps.DirectionsService();
        const request = {
            origin: {lat: Number.parseFloat(originCoords.lat), lng: Number.parseFloat(originCoords.lng)},
            destination:  {lat: Number.parseFloat(destinationCoords.lat), lng: Number.parseFloat(destinationCoords.lng)},
            travelMode: 'DRIVING'
        };
        const data = await directionsService.route(request)
        
          let polylines = [];
          if (data.routes && data.routes.length > 0) {
            const steps = data.routes[0].legs[0].steps;
            steps.forEach(item => {
              const points = decode(item.polyline.points);
              points.forEach(poly => {
                polylines.push({
                  lat: poly[0],
                  lng: poly[1]
                })
              })
            });
            console.log({polylines})
            return polylines;
          } else {
            return [];
          }
      } catch (error) {
        console.log(error);
        return [];
      }
    };
    // const getDirections = async (originCoords, destinationCoords) => {
    //   const originLatLng = `${originCoords.lat},${originCoords.lng}`;
    //   const destinationLatLng = `${destinationCoords.lat},${destinationCoords.lng}`;
    //   try {
    //       let url = `https://maps.googleapis.com/maps/api/directions/json?origin=${originLatLng}&destination=${destinationLatLng}&mode=driving&key=${mapKey}`;
    //       // let url = `https://maps.googleapis.com/maps/api/directions/json?origin=${originLatLng}&destination=${destinationLatLng}&mode=driving&key=${mapKey}`;
    //       const response = await fetch(url);
    //       const data = await response.json();
    //       let polylines = [];
    //       if (data.routes && data.routes.length > 0) {
    //         const steps = data.routes[0].legs[0].steps;
    //         steps.forEach(item => {
    //           const points = decode(item.polyline.points);
    //           points.forEach(poly => {
    //             polylines.push({
    //               lat: poly[0],
    //               lng: poly[1]
    //             })
    //           })
    //         });
    //         console.log({polylines})
    //         return polylines;
    //       } else {
    //         return [];
    //       }
    //   } catch (error) {
    //     console.log(error);
    //     return [];
    //   }
    // };

    return {
        originCoords,
        geocodeAddress,
        getDirections,
        // polylines
    }
}