import 'dart:convert';
import 'dart:developer';

import 'package:dio/dio.dart';
import 'package:flutter_polyline_points/flutter_polyline_points.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:http/http.dart' as http;
import '../constant/app/app_constants.dart';
import '../shared/find_location_maps/model/prediction_model.dart';
import '../shared/model/near_by_search_model.dart';

class MapServices {
  
  Future<List<PlaceDetails>> getNearbyPlaces(double latitude, double longitude,
      String searchKey, int radius, String type) async {
    List<PlaceDetails> result = [];
    var url = Uri.parse(
        'https://maps.googleapis.com/maps/api/place/autocomplete/json?input=$searchKey&language=vi&location=$latitude%2C$longitude&radius=$radius&strictbounds=true&type=$type&key=${ApplicationConstants.MAP_KEY}');
    log("URL LIST: $url");
    var response = await http.post(url);
    final placesAutocompleteResponse =
        PlacesAutocompleteResponse.fromJson(jsonDecode(response.body));
    if (placesAutocompleteResponse.predictions != null) {
      for (int i = 0; i < placesAutocompleteResponse.predictions!.length; i++) {
        var url =
            "https://maps.googleapis.com/maps/api/place/details/json?placeid=${placesAutocompleteResponse.predictions![i].placeId}&language=vi&key=${ApplicationConstants.MAP_KEY}";
        log(url.toString());
        Response response = await Dio().get(
          url,
        );
        PlaceDetails placeDetails = PlaceDetails.fromJson(response.data);
        result.add(placeDetails);
        // displayLocation(placesAutocompleteResponse.predictions![i], i);
      }
      return result;
    } else {
      log("null");
      return [];
    }
  }

  Future<List<LatLng>> findTheWay(LatLng origin, LatLng destination) async {
    List<LatLng> polylineCoordinates = [];
    PolylinePoints polylinePoints = PolylinePoints();

    PolylineResult result = await polylinePoints.getRouteBetweenCoordinates(
        ApplicationConstants.MAP_KEY,
        PointLatLng(origin.latitude, origin.longitude),
        PointLatLng(destination.latitude, destination.longitude),
        travelMode: TravelMode.driving,
        optimizeWaypoints: true);
    if (result.points.isNotEmpty) {
      for (var point in result.points) {
        polylineCoordinates.add(LatLng(point.latitude, point.longitude));
      }
      return polylineCoordinates;
    } else {
      log("Lỗi khi tìm đường");
      return [];
    }
  }

}