
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:healthcare_pharmacy/dashboard.dart';
import 'package:healthcare_pharmacy/keys.dart';
import 'package:healthcare_pharmacy/settings.dart';
import 'package:flutter/services.dart';
import 'dart:io' show File, Platform;
import 'package:google_maps_flutter_android/google_maps_flutter_android.dart';
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
import 'package:location/location.dart' as locationmap;
import 'google_maps_place_picker_mb/src/models/pick_result.dart';
import 'google_maps_place_picker_mb/src/place_picker.dart';

class Deliverboy extends StatefulWidget {
  const Deliverboy({Key? key}) : super(key: key);

  @override
  State<Deliverboy> createState() => _deliverboyState();
}

class _deliverboyState extends State<Deliverboy> {

  TextEditingController pharmacyNameController = TextEditingController();
  TextEditingController deliverNameController = TextEditingController();
  TextEditingController deliveryPhoneNumberController = TextEditingController();
  TextEditingController deliveryAlternativePhoneNumberController = TextEditingController();
  TextEditingController deliveryAddressCapturingController = TextEditingController();


  String _currentAddress ='';
  String address1 = '';
  String address2 = '';
  String city = '';
  String state = '';
  String zip = '';
  String status = '';
  double lat=0;
  double lng=0;

  PickResult? selectedPlace;

  bool _mapsInitialized = false;
  final String _mapsRenderer = "latest";

  var kInitialPosition = const LatLng(15.462477, 78.717401);

  locationmap.Location location = locationmap.Location();

  final GoogleMapsFlutterPlatform mapsImplementation =
      GoogleMapsFlutterPlatform.instance;

  void initRenderer() {
    if (_mapsInitialized) return;
    if (mapsImplementation is GoogleMapsFlutterAndroid) {
      switch (_mapsRenderer) {
        case "legacy":
          (mapsImplementation as GoogleMapsFlutterAndroid)
              .initializeWithRenderer(AndroidMapRenderer.legacy);
          break;
        case "latest":
          (mapsImplementation as GoogleMapsFlutterAndroid)
              .initializeWithRenderer(AndroidMapRenderer.latest);
          break;
      }
    }
    setState(() {
      _mapsInitialized = true;
    });
  }




  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar:AppSettings.appBar('Add Deliveryboy'),
      body: SafeArea(
          child: SingleChildScrollView(
            child: Column(
              children: <Widget>[
                const SizedBox(
                  height: 15,
                ),
                Container(
                    height: MediaQuery.of(context).size.height * .15,
                    width: double.infinity,
                    child: Image(
                      image: const AssetImage('images/logo.png'),
                      height: MediaQuery.of(context).size.height * .25,
                    )),

                const SizedBox(
                  height: 15,
                ),
                Container(
                  //padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
                  padding: const EdgeInsets.all(10),
                  child: TextFormField(
                    cursorColor: greyColor,
                    controller: pharmacyNameController,
                    textCapitalization: TextCapitalization.characters,
                    decoration: const InputDecoration(
                      prefixIcon: Icon(
                        Icons.propane_tank,
                        color: greyColor,
                      ),
                      border: OutlineInputBorder(
                          borderSide: BorderSide(color: greyColor)),
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: greyColor),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: greyColor),
                      ),
                      labelText: 'Enter pharmacy name',
                      labelStyle: TextStyle(
                        color: greyColor, //<-- SEE HERE
                      ),
                    ),
                  ), //tanker name
                ),


                const SizedBox(
                  height: 15,
                ),
                Container(
                  //padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
                  padding: const EdgeInsets.all(10),
                  child: TextFormField(
                    cursorColor: greyColor,
                    controller: deliverNameController,
                    textCapitalization: TextCapitalization.characters,
                    decoration: const InputDecoration(
                      prefixIcon: Icon(
                        Icons.propane_tank,
                        color: greyColor,
                      ),
                      border: OutlineInputBorder(
                          borderSide: BorderSide(color: greyColor)),
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: greyColor),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: greyColor),
                      ),
                      labelText: 'Enter deliveryboy name',
                      labelStyle: TextStyle(
                        color: greyColor, //<-- SEE HERE
                      ),
                    ),
                  ), //tanker name
                ),
                const SizedBox(
                  height: 5,
                ),
                Container(
                  padding: const EdgeInsets.all(10),
                  child: TextFormField(
                    cursorColor: greyColor,
                    controller: deliveryPhoneNumberController,
                    keyboardType: TextInputType.number,
                    maxLength: 10,
                    decoration: const InputDecoration(
                      prefixIcon: Icon(
                        Icons.phone_android,
                        color: greyColor,
                      ),
                      border: OutlineInputBorder(
                          borderSide: BorderSide(color: greyColor)),
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: greyColor),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: greyColor),
                      ),
                      labelText: 'Enter phone number',
                      labelStyle: TextStyle(
                        color: greyColor, //<-- SEE HERE
                      ),
                    ),
                  ),
                ), //phone number
                const SizedBox(
                  height: 5,
                ),

                Container(
                  padding: const EdgeInsets.all(10),
                  child: TextFormField(
                    cursorColor: greyColor,
                    controller: deliveryAlternativePhoneNumberController,
                    keyboardType: TextInputType.number,
                    maxLength: 10,
                    decoration: const InputDecoration(
                      prefixIcon: Icon(
                        Icons.phone_android,
                        color: greyColor,
                      ),
                      border: OutlineInputBorder(
                          borderSide: BorderSide(color: greyColor)),
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: greyColor),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: greyColor),
                      ),
                      labelText: 'Enter alternative phone number',
                      labelStyle: TextStyle(
                        color: greyColor, //<-- SEE HERE
                      ),
                    ),
                  ),
                ), //alternative phone number
                const SizedBox(
                  height: 5,
                ),


                GestureDetector(
                  child:Container(
                    padding: const EdgeInsets.all(10),
                    child: TextFormField(
                      cursorColor: greyColor,
                      controller: deliveryAddressCapturingController,
                      onTap:()
                      {

                        //=============================================================================================
                        location.serviceEnabled().then((value) {
                          if (value) {
                            initRenderer();
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) {
                                  return PlacePicker(
                                    resizeToAvoidBottomInset: false,
                                    hintText: "Find a place ...",
                                    searchingText: "Please wait ...",
                                    selectText: "Select place",
                                    outsideOfPickAreaText: "Place not in area",
                                    initialPosition: kInitialPosition,
                                    useCurrentLocation: true,
                                    selectInitialPosition: true,
                                    usePinPointingSearch: true,
                                    usePlaceDetailSearch: true,
                                    zoomGesturesEnabled: true,
                                    zoomControlsEnabled: true,
                                    onMapCreated: (GoogleMapController controller) {},
                                    onPlacePicked: (PickResult result) {
                                      setState(() {
                                        selectedPlace = result;
                                        lat=selectedPlace!.geometry!.location.lat;
                                        lng=selectedPlace!.geometry!.location.lng;
                                        if(selectedPlace!.types!.length==1){
                                          deliveryAddressCapturingController.text =
                                          selectedPlace!.formattedAddress!;
                                        }
                                        else{
                                          deliveryAddressCapturingController.text =selectedPlace!.name!+', '+selectedPlace!.formattedAddress!;
                                        }
                                        Navigator.of(context).pop();
                                      });
                                    },
                                    onMapTypeChanged: (MapType mapType) {},
                                    apiKey: Platform.isAndroid
                                        ? APIKeys.androidApiKey
                                        : APIKeys.iosApiKey,
                                    forceAndroidLocationManager: true,
                                  );
                                },
                              ),
                            );
                          } else {
                            showGeneralDialog(
                              context: context,
                              pageBuilder: (context, x, y) {
                                return Scaffold(
                                  backgroundColor: Colors.grey.withOpacity(.5),
                                  body: Center(
                                    child: Container(
                                      width: double.infinity,
                                      height: 150,
                                      padding:
                                      const EdgeInsets.symmetric(horizontal: 20),
                                      child: Card(
                                        child: Padding(
                                          padding: const EdgeInsets.all(10.0),
                                          child: Column(
                                            mainAxisAlignment: MainAxisAlignment.center,
                                            children: [
                                              const Text(
                                                "Please enable the location",
                                                style: TextStyle(
                                                  fontSize:18,
                                                  fontWeight: FontWeight.w500,
                                                ),
                                              ),
                                              const SizedBox(
                                                height: 20,
                                              ),
                                              ElevatedButton(
                                                onPressed: () {
                                                  Navigator.pop(context);
                                                },
                                                child: const Text("Cancel"),
                                              ),
                                            ],
                                          ),
                                        ),
                                      ),
                                    ),
                                  ),
                                );
                              },
                            );
                          }
                        });

                        //=====================================================================================

                        // _getCurrentPosition();
                      },
                      keyboardType: TextInputType.streetAddress,
                      readOnly: false,
                      decoration: const InputDecoration(
                        prefixIcon: Icon(
                          Icons.location_on_rounded,
                          color: greyColor,
                        ),
                        border: OutlineInputBorder(
                            borderSide: BorderSide(color: greyColor)),
                        focusedBorder: OutlineInputBorder(
                          borderSide: BorderSide(color: greyColor),
                        ),
                        enabledBorder: OutlineInputBorder(
                          borderSide: BorderSide(color: greyColor),
                        ),
                        labelText: 'select address from MAP',
                        labelStyle: TextStyle(
                          color: greyColor, //<-- SEE HERE
                        ),
                      ),

                    ),
                  ),
                  /*   onTap: ()
                        {
                        },*///address
                ),



                const SizedBox(
                  height: 5,
                ),
                Container(
                    width: MediaQuery.of(context).size.width * .99,
                    height: 50,
                    padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
                    child: ElevatedButton(
                      style: ElevatedButton.styleFrom(
                        primary: primaryColor, // background
                        onPrimary: Colors.white, // foreground
                      ),
                      onPressed: () async {

                        if (deliverNameController.text != '' &&
                            deliveryPhoneNumberController.text != ''
                        ) {
                          AppSettings.preLoaderDialog(context);

                          var payload = new Map<String, dynamic>();
                          payload["pharmacyname"] = pharmacyNameController.text.toString();
                          payload["Name"] = deliverNameController.text.toString();
                          payload["phone"] = deliveryPhoneNumberController.text.toString();
                          payload["alternativeContactNumber"] = deliveryAlternativePhoneNumberController.text.toString();
                          payload["address"] = deliveryAddressCapturingController.text;
                          payload["city"] = city;
                          payload["state"] = state;
                          payload["zip"] = zip;
                          payload["latitude"] = lat;
                          payload["longitude"] = lng;
                          payload["status"] = status;
                          bool deliveryboyStatus = await AppSettings.addDeliverboy(payload);

                              try {
                                if (deliveryboyStatus) {
                                  AppSettings.longSuccessToast(
                                      "Deliverboy Created Successfully");
                              deliverNameController.text= '';
                               deliveryPhoneNumberController.text= '';
                              deliveryAlternativePhoneNumberController.text= '';
                                  Navigator.of(context,rootNavigator: true).pop();
                                  await Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                        builder: (context) => const Dashboard()),
                                  );

                      } else {
                                  Navigator.of(context,rootNavigator: true).pop();
                       AppSettings.longFailedToast("Deliverboy not  Created Successfully");
                 }
                      } catch (exception) {
                      print(exception);
                         }
                      }
                           else {
                         AppSettings.longFailedToast("Please enter valid details");
                           }
                     },

                      child: const Text(
                        'Add Deliverboy',
                        style: TextStyle(
                          fontSize: 25,
                        ),
                      ),
                    )),

              ],
            ),
          )),
    );
  }
}
