import 'package:flutter/cupertino.dart';
import 'package:geolocator/geolocator.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class DistanceService {
  static const String GOOGLE_MAPS_API_KEY = 'DEIN_API_KEY_HIER';

  static Future<Position> getCurrentLocation() async {
    bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      throw Exception('Location services sind deaktiviert');
    }

    LocationPermission permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
    }

    return await Geolocator.getCurrentPosition();
  }

  // Adresse in Koordinaten umwandeln (Geocoding)
  static Future<Map<String, double>> getCoordinates(String address) async {
    String url =
        'https://maps.googleapis.com/maps/api/geocode/json'
        '?address=${Uri.encodeComponent(address)}'
        '&key=AIzaSyB5_1ftLnoswoy59FzNFkrQ7SSDma5eu5E';

    final response = await http.get(Uri.parse(url));

    if (response.statusCode == 200) {
      var json = jsonDecode(response.body);

      if (json['results'].isNotEmpty) {
        var location = json['results'][0]['geometry']['location'];
        return {
          'lat': location['lat'],
          'lng': location['lng'],
        };
      }
      throw Exception('Adresse nicht gefunden');
    }
    throw Exception('Geocoding Fehler: ${response.statusCode}');
  }

  // Distanz berechnen
  static Future<double> getDistanceByRoad(String address) async {
    try {
      Position currentPos = await getCurrentLocation();
      Map<String, double> coords = await getCoordinates(address);

      String origin = "${currentPos.latitude},${currentPos.longitude}";
      String destination = "${coords['lat']},${coords['lng']}";

      String url =
          'https://maps.googleapis.com/maps/api/distancematrix/json'
          '?origins=$origin'
          '&destinations=$destination'
          '&key=AIzaSyB5_1ftLnoswoy59FzNFkrQ7SSDma5eu5E';

      final response = await http.get(Uri.parse(url));

      debugPrint(response.body);

      if (response.statusCode == 200) {
        var json = jsonDecode(response.body);

        if (json['rows'][0]['elements'][0]['status'] == 'OK') {
          int distanceMeters = json['rows'][0]['elements'][0]['distance']['value'];
          return distanceMeters / 1000; // In km
        } else {
          throw Exception('Route nicht gefunden');
        }
      } else {
        throw Exception('API Fehler: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('Fehler: $e');
    }
  }
}