import 'dart:io';

import 'package:google_maps_place_picker_mb_v2/google_maps_place_picker.dart';
import 'package:hmg_patient_app/config/config.dart';
import 'package:hmg_patient_app/config/shared_pref_kay.dart';
import 'package:hmg_patient_app/core/enum/viewstate.dart';
import 'package:hmg_patient_app/core/model/ImagesInfo.dart';
import 'package:hmg_patient_app/core/viewModels/AlHabibMedicalService/add_new_address_Request_Model.dart';
import 'package:hmg_patient_app/core/viewModels/AlHabibMedicalService/cmc_view_model.dart';
import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/pages/base/base_view.dart';
import 'package:hmg_patient_app/services/permission/permission_service.dart';
import 'package:hmg_patient_app/theme/colors.dart';
import 'package:hmg_patient_app/uitl/app_shared_preferences.dart';
import 'package:hmg_patient_app/uitl/app_toast.dart';
import 'package:hmg_patient_app/uitl/translations_delegate_base.dart';
import 'package:hmg_patient_app/uitl/utils.dart';
import 'package:hmg_patient_app/widgets/app_map/google_huawei_map.dart';
import 'package:hmg_patient_app/widgets/buttons/defaultButton.dart';
import 'package:hmg_patient_app/widgets/buttons/secondary_button.dart';
import 'package:hmg_patient_app/widgets/others/app_scaffold_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

// import 'package:flutter_hms_gms_availability/flutter_hms_gms_availability.dart';
import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart' as gmaps;
import 'package:huawei_hmsavailability/huawei_hmsavailability.dart';
import 'package:provider/provider.dart';

class CMCLocationPage extends StatefulWidget {
  final Function onPick;
  final double latitude;
  final double longitude;
  final dynamic model;

  const CMCLocationPage({Key? key, required this.onPick, required this.latitude, required this.longitude, this.model}) : super(key: key);

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

class _CMCLocationPageState extends State<CMCLocationPage> {
  double latitude = 0;
  double longitude = 0;
  bool showCurrentLocation = false;
  late Function onPick;
  bool isHuawei = false;
  late Placemark selectedPlace;
  late AppMap appMap;
  static gmaps.CameraPosition _kGooglePlex = gmaps.CameraPosition(
    target: gmaps.LatLng(37.42796133580664, -122.085749655962),
    zoom: 14.4746,
  );
  late gmaps.LatLng currentPostion;
  AppSharedPreferences sharedPref = AppSharedPreferences();
  late HmsApiAvailability hmsApiAvailability;

  @override
  void initState() {
    hmsApiAvailability = HmsApiAvailability();
    checkIsHuawei();

    appMap = AppMap(
      _kGooglePlex.toMap() as Map<dynamic, dynamic>,
      // changed by Aamir
      onCameraMove: () {
        _updatePosition(_kGooglePlex);
        // changed by Aamir Huawei & Google Issue may Be
      },
      onMapCreated: () {
        currentPostion = gmaps.LatLng(widget.latitude, widget.longitude);
        latitude = widget.latitude;
        longitude = widget.longitude;
        _getUserLocation();
        setState(() {});
      },
      onCameraIdle: () async {
        List<Placemark> placemarks = await placemarkFromCoordinates(latitude, longitude);
        selectedPlace = placemarks[0];
        print(selectedPlace);
      },
    );

    onPick = widget.onPick;
    latitude = widget.latitude;
    longitude = widget.longitude;
    if (latitude == 0.0 && longitude == 0.0) {
      showCurrentLocation = true;
    }
    super.initState();
  }

  checkIsHuawei() async {
    await hmsApiAvailability!.isHMSAvailable().then((value) {
      isHuawei = value == 0 ? true : false;
    });
    print(isHuawei);
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    ProjectViewModel projectViewModel = Provider.of(context);

    return BaseView<CMCViewModel>(
      onModelReady: (model) {},
      builder: (_, model, widget) => AppScaffold(
        isShowDecPage: false,
        isShowAppBar: true,
        baseViewModel: model,
        showNewAppBar: true,
        showNewAppBarTitle: true,
        backgroundColor: CustomColors.appBackgroudGreyColor,
        description: TranslationBase.of(context).infoCMC,
        imagesInfo: [
          ImagesInfo(imageAr: 'https://hmgwebservices.com/Images/MobileApp/CMC/ar/0.png', imageEn: 'https://hmgwebservices.com/Images/MobileApp/CMC/en/0.png'),
        ],
        appBarTitle: TranslationBase.of(context).addNewAddress,
        body: isHuawei
            ? Column(
                children: [
                  Expanded(
                    child: Stack(
                      alignment: Alignment.center,
                      children: [
                        if (appMap != null) appMap,
                        Container(
                          margin: EdgeInsets.only(bottom: 50.0),
                          child: Icon(
                            Icons.place,
                            color: CustomColors.accentColor,
                            size: 50,
                          ),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    padding: const EdgeInsets.only(left: 20, right: 20, top: 14, bottom: 14),
                    child: DefaultButton(TranslationBase.of(context).addNewAddress, () async {
                      AddNewAddressRequestModel addNewAddressRequestModel = new AddNewAddressRequestModel(
                        customer: Customer(addresses: [
                          Addresses(
                              address1: selectedPlace.street,
                              address2: selectedPlace.street,
                              customerAttributes: "",
                              city: selectedPlace.administrativeArea,
                              createdOnUtc: "",
                              id: "0",
                              faxNumber: "",
                              phoneNumber: projectViewModel.user!.mobileNumber,
                              province: selectedPlace.administrativeArea,
                              countryId: 69,
                              latLong: latitude.toStringAsFixed(6) + "," + longitude.toStringAsFixed(6),
                              country: selectedPlace.country,
                              zipPostalCode: selectedPlace.postalCode,
                              email: projectViewModel.user!.emailAddress)
                        ]),
                      );
                      await model.addAddressInfo(addNewAddressRequestModel: addNewAddressRequestModel);
                      if (model.state == ViewState.ErrorLocal) {
                        Utils.showErrorToast(model.error);
                      } else {
                        AppToast.showSuccessToast(message: "Address Added Successfully");
                      }
                      Navigator.of(context).pop(addNewAddressRequestModel);
                    }),
                  ),
                ],
              )
            : PlacePicker(
                apiKey: GOOGLE_API_KEY,
                enableMyLocationButton: true,
                automaticallyImplyAppBarLeading: false,
                autocompleteOnTrailingWhitespace: true,
                selectInitialPosition: true,
                autocompleteLanguage: projectViewModel.currentLanguage,
                enableMapTypeButton: true,
                searchForInitialValue: false,
                onPlacePicked: (PickResult result) {
                  print(result.adrAddress);
                },
                selectedPlaceWidgetBuilder: (_, selectedPlace, state, isSearchBarFocused) {
                  print("state: $state, isSearchBarFocused: $isSearchBarFocused");

                  return isSearchBarFocused
                      ? Container()
                      : FloatingCard(
                          bottomPosition: 0.0,
                          leftPosition: 0.0,
                          rightPosition: 0.0,
                          width: 500,
                          borderRadius: BorderRadius.circular(12.0),
                          child: state == SearchingState.Searching
                              ? Center(child: CircularProgressIndicator())
                              : Container(
                                  margin: EdgeInsets.all(12),
                                  child: Column(
                                    children: [
                                      SecondaryButton(
                                        color: CustomColors.accentColor,
                                        textColor: Colors.white,
                                        onTap: () async {
                                          print(selectedPlace);
                                          AddNewAddressRequestModel addNewAddressRequestModel = new AddNewAddressRequestModel(
                                            customer: Customer(
                                              addresses: [
                                                Addresses(
                                                  address1: selectedPlace!.formattedAddress,
                                                  address2: selectedPlace.formattedAddress,
                                                  customerAttributes: "",
                                                  city: "",
                                                  createdOnUtc: "",
                                                  id: "0",
                                                  latLong: selectedPlace.geometry!.location.lat.toString() + "," + selectedPlace.geometry!.location.lng.toString(),
                                                  email: "",
                                                )
                                              ],
                                            ),
                                          );

                                          selectedPlace.addressComponents!.forEach((e) {
                                            if (e.types.contains("country")) {
                                              addNewAddressRequestModel.customer!.addresses![0].country = e.longName;
                                            }
                                            if (e.types.contains("postal_code")) {
                                              addNewAddressRequestModel.customer!.addresses![0].zipPostalCode = e.longName;
                                            }
                                            if (e.types.contains("locality")) {
                                              addNewAddressRequestModel.customer!.addresses![0].city = e.longName;
                                            }
                                          });

                                          await model.addAddressInfo(addNewAddressRequestModel: addNewAddressRequestModel);
                                          if (model.state == ViewState.ErrorLocal) {
                                            Utils.showErrorToast(model.error);
                                          } else {
                                            onPick();
                                            AppToast.showSuccessToast(message: "Address Added Successfully");
                                          }
                                          Navigator.of(context).pop();
                                        },
                                        label: TranslationBase.of(context).addNewAddress,
                                      ),
                                    ],
                                  ),
                                ),
                        );
                },
                initialPosition: gmaps.LatLng(latitude, longitude),
                useCurrentLocation: showCurrentLocation,
              ),
      ),
    );
  }

  void _getUserLocation() async {
    if (await this.sharedPref.getDouble(USER_LAT) != null && await this.sharedPref.getDouble(USER_LONG) != null) {
      var lat = await this.sharedPref.getDouble(USER_LAT);
      var long = await this.sharedPref.getDouble(USER_LONG);
      latitude = lat;
      longitude = long;
      currentPostion = gmaps.LatLng(lat, long);
      setMap();
    } else {
      if (await PermissionService.isLocationEnabled()) {
        Geolocator.getLastKnownPosition().then((value) {
          latitude = value!.latitude;
          longitude = value.longitude;
          currentPostion = gmaps.LatLng(latitude, longitude);
          setMap();
        });
      } else {
        if (Platform.isAndroid) {
          Utils.showPermissionConsentDialog(context, TranslationBase.of(context).locationPermissionDialog, () {
            Geolocator.getLastKnownPosition().then((value) {
              latitude = value!.latitude;
              longitude = value.longitude;
              currentPostion = gmaps.LatLng(latitude, longitude);
              setMap();
            });
          });
        } else {
          Geolocator.getLastKnownPosition().then((value) {
            latitude = value!.latitude;
            longitude = value.longitude;
            setMap();
          });
        }
      }
    }
  }

  setMap() {
    setState(() {
      _kGooglePlex = gmaps.CameraPosition(
        target: currentPostion,
        zoom: 14.4746,
      );
      appMap.moveTo(cameraPostion: _kGooglePlex);
    });
  }

  void _updatePosition(gmaps.CameraPosition _position) {
    print(_position);
    latitude = _position.target.latitude;
    longitude = _position.target.longitude;
  }
}
