import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

import '../../../../Controller/Createorder/Createordercontroller.dart';
import '../../../../Controller/Createorder/Pickup/Googlemap/Googlemapcontroller.dart';
import '../../../../Helper/Constants/Colorconstants.dart';



class PickupGoogleMapView extends StatelessWidget {
  final double lat;
  final double long;

  PickupGoogleMapView ({Key? key,required this.lat, required this.long,}) : super(key: key);

  PickupGoogleMapsController googleMapController = Get.put(PickupGoogleMapsController());
  CreateOrderController createOrderController = Get.put(CreateOrderController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(

        elevation: 0.5,
        backgroundColor: ColorConstants.primaryColor,
        title: const Text(
          'Select Location',
          style: TextStyle(
            color: Colors.white,
          ),
        ),
      ),
      body: GetBuilder<PickupGoogleMapsController>(
          initState: (_){
            PickupGoogleMapsController.currentLatitude =lat;
            PickupGoogleMapsController.currentLongitude =long;
            PickupGoogleMapsController.center = LatLng(PickupGoogleMapsController.currentLatitude!, PickupGoogleMapsController.currentLongitude!);
            googleMapController.kGooglePlex = CameraPosition(
              target: LatLng(PickupGoogleMapsController.currentLatitude!, PickupGoogleMapsController.currentLongitude!),
              zoom: 14.4746,
            );
            googleMapController.getCountry();
          },
          builder: (controller) {
            return Container(
              child: Column(
                // fit: StackFit.loose,
                children: [
                  Container(
                      child: Row(
                        children: [
                          Container(
                            width: MediaQuery.of(context).size.width,
                            color: Colors.white,
                            height: 60,
                            padding: EdgeInsets.symmetric(horizontal: 8, vertical: 8),
                            child: TextField(
                              controller: controller.searchController,
                              decoration: InputDecoration(
                                  suffixIcon: Icon(Icons.search),
                                  enabledBorder: OutlineInputBorder(
                                    borderSide: BorderSide(
                                      color: Colors.grey[300]!,
                                    ),
                                  ),
                                  focusedBorder: OutlineInputBorder(
                                    borderSide: BorderSide(
                                      color: ColorConstants.primaryColor,
                                    ),
                                  ),
                                  labelText: 'Search',
                                  labelStyle: TextStyle(color: Colors.black45)),
                              onChanged: (text) async {
                                if(text.isEmpty){
                                  controller.pickupPredictions.clear();
                                  FocusScope.of(context).unfocus();
                                  controller.update();
                                }
                                else {
                                  controller
                                      .onSearchPickupTextChanged(
                                      text);
                                }
                              },
                            ),
                          ),
                        ],
                      )),
                  controller.pickupPredictions.isNotEmpty?Container(
                    height: Get.height*0.20,
                    width: Get.width,
                    decoration: BoxDecoration(color: ColorConstants.secondaryColor,borderRadius: BorderRadius.circular(1)),
                    child: Obx(() {
                      return ListView.builder(
                        itemCount:  controller.pickupPredictions.length,
                        itemBuilder: (context, index) {
                          final prediction =
                          controller.pickupPredictions[index]['description'];
                          return ListTile(
                            title: Text(prediction,style: TextStyle(color: ColorConstants.darkGreyColor),),
                            onTap: () {
                              final placeId =
                              controller.pickupPredictions[index]['place_id'];
                              controller.getPickupPlaceDetails(placeId,prediction);
                              googleMapController.searchController.clear();
                              FocusScope.of(context).unfocus();
                            },
                          );
                        },
                      );

                    }),):SizedBox(),
                  Expanded(
                    flex: 7,
                    child: GoogleMap(
                      myLocationButtonEnabled: true,
                      myLocationEnabled: true,
                      mapType: MapType.normal,
                      initialCameraPosition: controller.kGooglePlex!,
                      markers: controller.markers,
                      onCameraMove: (position) {
                        if (controller.markers.length >= 1) {
                          controller.markers.clear();
                        }
                        PickupGoogleMapsController.center = position.target;
                        controller.update();
                        print('positionsssprint$position');
                        onAddMarkerButtonPressed(PickupGoogleMapsController.center!);
                        // Update the markers for the updated position.zoom
                      },
                      onCameraIdle: () async {
                        if (controller.markers.length >= 1) {
                          controller.markers.clear();
                        }
                        await controller.getAddressFromLatLong(
                            PickupGoogleMapsController.center!.latitude, PickupGoogleMapsController.center!.longitude);
                        controller.update();
                        print("addressOnCameraIdle${controller.address}");

                        onAddMarkerButtonPressed(PickupGoogleMapsController.center!);
                      },
                      onTap: (latLong) async {
                        if (controller.markers.length >= 1) {
                          controller.markers.clear();
                        }
                        PickupGoogleMapsController.center = latLong;
                        print('_lastMapPosition${PickupGoogleMapsController.center}');
                       await controller.getAddressFromLatLong(
                           PickupGoogleMapsController.center!.latitude, PickupGoogleMapsController.center!.longitude);
                        print('address${controller.address}');
                        controller.update();
                        onAddMarkerButtonPressed(PickupGoogleMapsController.center!);
                      },
                      onMapCreated: (GoogleMapController controllers) {
                        controller.mapController = controllers;
                        controller.controllers.complete(controllers);
                      },
                    ),
                  ),
                ],
              ),
            );
          }
      ),
      floatingActionButton: FloatingActionButton(
          onPressed: () async {
            if (googleMapController.markers.length >= 1) {
              googleMapController.markers.clear();
            }
             googleMapController.getAddressFromLatLong(
                lat, long);
            PickupGoogleMapsController.center = LatLng(lat,long);
            googleMapController.markers.add(
              Marker(
                markerId: MarkerId(PickupGoogleMapsController.center.toString()),
                position: PickupGoogleMapsController.center!,
                draggable: true,
                onDragEnd: (latLong) async {
                  print('latLongDrag$latLong');
                  PickupGoogleMapsController.center = latLong;
                   await googleMapController.getAddressFromLatLong(
                      latLong.latitude, latLong.longitude);
                  googleMapController.update();
                },
                onDrag: (latLong) {
                  PickupGoogleMapsController.center = latLong;
                  googleMapController.update();
                },
                infoWindow: InfoWindow(
                  title: 'My Location',
                ),
                icon: BitmapDescriptor.defaultMarker,
              ),
            );
            googleMapController.kGooglePlex = CameraPosition(
              target: LatLng(lat, long),
              zoom: 14.4746,
            );
            googleMapController.goToThePosition(googleMapController.kGooglePlex);
            googleMapController.update();
            print("addressOnCameraIdle${googleMapController.address}");
            // _onAddMarkerButtonPressed(_center!);
          },
          child: Icon(Icons.refresh, color: Colors.white)),
      floatingActionButtonLocation: FloatingActionButtonLocation.startFloat,
      bottomNavigationBar: GetBuilder<PickupGoogleMapsController>(
          builder: (controller) {
            return Container(
              height: 120,
              color: Colors.white,
              padding: EdgeInsets.all(8),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Row(
                    children: [
                      Icon(Icons.location_on),
                      SizedBox(
                        width: 10,
                      ),
                      Expanded(
                        child: Text(
                          controller.pickupAddressController.text??'',
                          maxLines: 2,
                          softWrap: true,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ],
                  ),
                  SizedBox(
                    height: 8,
                  ),
                  Container(
                    height: 50,
                    margin: EdgeInsets.only(left: 15,right: 15),
                    decoration: BoxDecoration(
                      color: ColorConstants.primaryColor,
                      borderRadius: BorderRadius.circular(20),
                    ),
                    child: InkWell(
                      onTap: () {
                        createOrderController.pickupCityController.text = controller.pickupCityController.text;
                        createOrderController.pickupStateController.text = controller.pickupStateController.text ;
                        createOrderController.pickupSuburbController.text = controller.pickupSuburbController.text ;
                        createOrderController.pickupPostcodeController.text = controller.pickupPostcodeController.text ;
                        createOrderController.pickupAddressController.text = controller.pickupAddressController.text ;
                        createOrderController.pickupAddressController.text = controller.fromAddress??'';
                        createOrderController.fromLatitude = controller.fromLatitude;
                        createOrderController.fromLongitude = controller.fromLongitude;
                        print('pickupAddressControllergooglemap ${controller.pickupAddressController.text}');
                        controller.update();
                        Navigator.pop(context);
                      },
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            'Continue',
                            style: TextStyle(color: Colors.white),
                          ),
                        ],
                      ),
                    ),
                  )
                ],
              ),
            );
          }
      ),
    );
  }

  onAddMarkerButtonPressed(latLong) {
    googleMapController.update();
    googleMapController.markers.add(
      Marker(
        markerId: MarkerId(PickupGoogleMapsController.center.toString()),
        position: PickupGoogleMapsController.center!,
        draggable: true,
        onDragEnd: (latLong) async {
          print('latLongDrag$latLong');
          PickupGoogleMapsController.center = latLong;
          googleMapController.address = googleMapController.getAddressFromLatLong(
              latLong.latitude, latLong.longitude);
          googleMapController.update();
        },
        onDrag: (latLong) {
          PickupGoogleMapsController.center = latLong;
          googleMapController.update();
        },
        infoWindow: InfoWindow(
          title: 'My Location',
          // snippet: googleMapController.address,

        ),
        icon: BitmapDescriptor.defaultMarker,
      ),
    );
  }

}
