import 'dart:async';
import 'dart:developer';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_polyline_points/flutter_polyline_points.dart';
import 'package:get/get.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:location/location.dart';
import 'location_controller.dart';


class OrderTrackingPage extends StatefulWidget {
  var lat;
  var lng;
  var d_lat;
  var d_lng;
  var u_address;

  OrderTrackingPage({
    this.lat,
    this.lng,
    this.d_lat,
    this.d_lng,
    this.u_address

  });

  @override
  OrderTrackingPageState createState() => OrderTrackingPageState();
}

class OrderTrackingPageState extends State<OrderTrackingPage> {
  final Completer<GoogleMapController> mapController = Completer();
  PolylinePoints polylinePoints = PolylinePoints();
  double latitude=0;
  double longitude=0;
  double d_latitude=0;
  double d_longitude=0;
  String u_address = '';
  LocationData? currentLocation;


  String googleAPiKey ="AIzaSyDJpK9RVhlBejtJu9xSGfneuTN6HOfJgSM";

  Set<Marker> markers = {};
  Map<PolylineId, Polyline> polylines = {};

  late LatLng startLocation ;
  late LatLng user_location;
  LocationController locationController = Get.put(LocationController());
  double distance = 0.0;


  @override
  void initState() {
    super.initState();
    latitude=widget.lat;
    longitude=widget.lng;
    d_latitude=widget.d_lat;
    d_longitude=widget.d_lng;
    u_address=widget.u_address;


     user_location =  LatLng(widget.lat,widget.lng);
     startLocation =  LatLng(widget.d_lat,widget.d_lng);

    LatLng delivery_Location =  LatLng(widget.d_lat,widget.d_lng);

    //LatLng endLocation =  LatLng(17.4968,78.3614);

    ever<LatLng?>(locationController.locationPosition, (value) {
      if (value != null) {
       // log("${value.latitude} ${value.longitude}");
        var latitude = value.latitude;
        var longitude = value.longitude;
        startLocation = LatLng(widget.d_lat, widget.d_lng);
        getDirections(user_location);
      }
    });
    getDirections(user_location); //fetch direction polylines from Google API
  }

  getDirections(user_location) async {
    markers.clear();

    markers.add(Marker(
      markerId: MarkerId(startLocation.toString()),
      position: startLocation,
      infoWindow: const InfoWindow(
        title: 'Starting Point',
        snippet: 'Start Marker',
      ),
      icon: locationController.pickupMarker ?? BitmapDescriptor.defaultMarker,
    ));

    markers.add(Marker(
      markerId: MarkerId(user_location.toString()),
      position: user_location, //position of marker
      infoWindow: const InfoWindow(
        title: 'Destination Point ',
        snippet: 'Destination Marker',
      ),
      icon: locationController.dropMarker ?? BitmapDescriptor.defaultMarker,
    ));

    List<LatLng> polylineCoordinates = [];

    PolylineResult result = await polylinePoints.getRouteBetweenCoordinates(
      googleAPiKey,
      PointLatLng(startLocation.latitude, startLocation.longitude),
      PointLatLng(user_location.latitude, user_location.longitude),
      travelMode: TravelMode.driving,
    );

    if (result.points.isNotEmpty) {
      for (var point in result.points) {
        polylineCoordinates.add(LatLng(point.latitude, point.longitude));
      }
    } else {
     // log(result.errorMessage ?? "Something went wrong");
    }

//polulineCoordinates is the List of longitute and latidtude.
    double totalDistance = 0;
    for(var i = 0; i < polylineCoordinates.length-1; i++){
      totalDistance += calculateDistance(
          polylineCoordinates[i].latitude,
          polylineCoordinates[i].longitude,
          polylineCoordinates[i+1].latitude,
          polylineCoordinates[i+1].longitude);
    }
    print(totalDistance);

    setState(() {
      distance = totalDistance;
    });

    addPolyLine(polylineCoordinates);
  }

  addPolyLine(List<LatLng> polylineCoordinates) async {
    PolylineId id = const PolylineId("poly");
    Polyline polyline = Polyline(
      polylineId: id,
      color: Colors.deepPurpleAccent,
      points: polylineCoordinates,
      width:8,
    );
    polylines[id] =polyline;

    var position = CameraPosition(
        target: LatLng(latitude,longitude),
        zoom: 16);

    final GoogleMapController controller = await mapController.future;
    controller.animateCamera(CameraUpdate.newCameraPosition(position));

    setState(() {});
  }


  double calculateDistance(lat1, lon1, lat2, lon2){
    var p = 0.017453292519943295;
    var a = 0.5 - cos((lat2 - lat1) * p)/2 +
        cos(lat1 * p) * cos(lat2 * p) *
            (1 - cos((lon2 - lon1) * p))/2;
    return 12742 * asin(sqrt(a));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          GoogleMap(
            //Map widget from google_maps_flutter package
            zoomGesturesEnabled: true,
            //enable Zoom in, out on map
            initialCameraPosition: CameraPosition(
              //innital position in map
              target: startLocation, //initial position
              zoom: 8.0, //initial zoom level
            ),

            markers: markers,
            //markers to show on map
            polylines: Set<Polyline>.of(polylines.values),
            //polylines
            mapType: MapType.normal,
            //map type
            onMapCreated: (controller) {
              //method called when map is created
              if (!mapController.isCompleted) {
                mapController.complete(controller);
              }
            },
          ),

          const SizedBox(
            height: 95,
          ),

          Positioned(
              bottom: 100,
              left: 50,
              child: Container(
                  child: Card(
                    child: Container(
                        padding: EdgeInsets.all(20),
                        child: Text("Total Distance: " + distance.toStringAsFixed(2) + " KM",
                            style: TextStyle(fontSize: 20, fontWeight:FontWeight.bold))
                    ),
                  )
              )),
        /*  const SizedBox(
            height: 30,
          ),
          Positioned(
              bottom: 80,
              left: 0,
              child: Container(
                  child: Card(
                    child: Container(
                        padding: EdgeInsets.all(20),

                        child: Text("User Address: " + u_address.toString() ,
                            style: TextStyle(fontSize: 15, fontWeight:FontWeight.bold,overflow: TextOverflow.ellipsis))
                    ),
                  )
              )),
          const SizedBox(
            height: 30,
          ),
          Positioned(
              bottom: 10,
              left: 50,
              child: Container(
                  child: Card(
                    child: Container(
                        padding: EdgeInsets.all(20),
                        child: Text("Total DistanceD: " + distance.toStringAsFixed(2) + " KM",
                            style: TextStyle(fontSize: 20, fontWeight:FontWeight.bold))
                    ),
                  )
              )),*/
        ],
      )

    );

  }
}
