import 'dart:io';

import 'package:diplomaticquarterapp/config/config.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/models/ambulanceRequest/locationDetails.dart';
import 'package:diplomaticquarterapp/theme/colors.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/app_map/google_huawei_map.dart';
import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:geocoding/geocoding.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:google_maps_place_picker_mb/google_maps_place_picker.dart';
import 'package:huawei_hmsavailability/huawei_hmsavailability.dart';
import 'package:provider/provider.dart';

class PickupLocationFromMap extends StatefulWidget {
  final Function(LocationDetails) onPick;
  final double latitude;
  final double longitude;
  final bool isWithAppBar;
  final String buttonLabel;
  final Color buttonColor;

  const PickupLocationFromMap({Key key, this.onPick, this.latitude, this.longitude, this.isWithAppBar = true, this.buttonLabel, this.buttonColor}) : super(key: key);

  @override
  State<PickupLocationFromMap> createState() => _PickupLocationFromMapState();
}

class _PickupLocationFromMapState extends State<PickupLocationFromMap> {
  bool isHuawei = false;
  Placemark selectedPlace;
  AppMap appMap;
  LatLng currentPostion;
  AppSharedPreferences sharedPref = AppSharedPreferences();
  double latitude = 0;
  double longitude = 0;

  HmsApiAvailability hmsApiAvailability;

  static CameraPosition kGooglePlex = CameraPosition(
    target: LatLng(24.126613,45.081137),
    zoom: 14.4746,
  );

  @override
  void initState() {
    if(Platform.isAndroid) {
      hmsApiAvailability = HmsApiAvailability();
      checkIsHuawei();
    }

    appMap = AppMap(
      kGooglePlex.toMap(),
      onCameraMove: (camera) {
        _updatePosition(camera);
      },
      onMapCreated: () {
        currentPostion = LatLng(widget.latitude, widget.longitude);
        latitude = widget.latitude;
        longitude = widget.longitude;
        setState(() {});
      },
      onCameraIdle: () async {
        List<Placemark> placemarks = await placemarkFromCoordinates(latitude, longitude);
        selectedPlace = placemarks[0];
        print(selectedPlace);
      },
    );
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    ProjectViewModel projectViewModel = Provider.of(context);
    return AppScaffold(
      isShowAppBar: true,
      showNewAppBarTitle: true,
      showNewAppBar: true,
      appBarTitle: TranslationBase.of(context).selectLocation,
      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).next, () async {
                    LocationDetails locationDetails = new LocationDetails();
                    locationDetails.lat = latitude;
                    locationDetails.long = longitude;
                    locationDetails.formattedAddress = selectedPlace.street;
                    widget.onPick(locationDetails);
                    Navigator.of(context).pop();
                  }),
                ),
              ],
            )
          : PlacePicker(
              apiKey: GOOGLE_API_KEY,
              enableMyLocationButton: true,
              automaticallyImplyAppBarLeading: false,
              autocompleteLanguage: projectViewModel.currentLanguage,
              enableMapTypeButton: true,
              selectInitialPosition: true,
              region: "SA",
              onPlacePicked: (PickResult result) {
                LocationDetails locationDetails = new LocationDetails();
                locationDetails.lat = latitude;
                locationDetails.long = longitude;
                locationDetails.formattedAddress = result.formattedAddress;
                print(result.adrAddress);
                widget.onPick(locationDetails);
                Navigator.of(context).pop();
              },
              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: DefaultButton(
                                  TranslationBase.of(context).next,
                                  () {
                                    LocationDetails locationDetails = new LocationDetails();
                                    locationDetails.lat = selectedPlace.geometry.location.lat;
                                    locationDetails.long = selectedPlace.geometry.location.lng;
                                    locationDetails.formattedAddress = selectedPlace.formattedAddress;
                                    widget.onPick(locationDetails);
                                    Navigator.of(context).pop();
                                  },
                                ),
                              ),
                      );
              },
              initialPosition: LatLng(projectViewModel.latitude, projectViewModel.longitude),
              useCurrentLocation: true,
            ),
    );
  }

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