import 'dart:async';
import 'dart:io';

import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/model/AlHabibMedicalService/HomeHealthCare/patient_er_insert_pres_order_request_model.dart';
import 'package:diplomaticquarterapp/core/service/AlHabibMedicalService/customer_addresses_service.dart';
import 'package:diplomaticquarterapp/core/viewModels/AlHabibMedicalService/home_health_care_view_model.dart';
import 'package:diplomaticquarterapp/pages/AlHabibMedicalService/HomeHealthCare/NewHomeHealthCare/new_Home_health_care_step_three_page.dart';
import 'package:diplomaticquarterapp/services/permission/permission_service.dart';
import 'package:diplomaticquarterapp/theme/colors.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart';
import 'package:diplomaticquarterapp/uitl/location_util.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/uitl/utils.dart';
import 'package:diplomaticquarterapp/uitl/utils_new.dart';
import 'package:diplomaticquarterapp/widgets/app_map/google_huawei_map.dart';
import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/select_location_dialog.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:google_maps_place_picker_mb/google_maps_place_picker.dart';

import 'location_page.dart';

class NewHomeHealthCareStepTowPage extends StatefulWidget {
  final Function(PickResult) onPick;
  final double latitude;
  final double longitude;
  final PatientERInsertPresOrderRequestModel patientERInsertPresOrderRequestModel;
  final Function changePageViewIndex;
  final HomeHealthCareViewModel model;

  const NewHomeHealthCareStepTowPage({Key key, this.onPick, this.latitude, this.longitude, this.patientERInsertPresOrderRequestModel, this.changePageViewIndex, this.model}) : super(key: key);

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

class _NewHomeHealthCareStepTowPageState extends State<NewHomeHealthCareStepTowPage> {
  double latitude = 0;
  double longitude = 0;
  AddressInfo _selectedAddress;
  bool showCurrentLocation = false;
  final Set<Marker> markers = new Set();
  AppMap appMap;
  AppSharedPreferences sharedPref = AppSharedPreferences();
  static CameraPosition _kGooglePlex = CameraPosition(
    target: LatLng(37.42796133580664, -122.085749655962),
    zoom: 14.4746,
  );
  LatLng currentPostion;
  Completer<GoogleMapController> mapController = Completer();
  LocationUtils locationUtils;

  @override
  void initState() {
    appMap = AppMap(
      _kGooglePlex.toMap(),
      onCameraMove: (camera) {
        _updatePosition(camera);
      },
      onMapCreated: () {
        _getUserLocation();
        setState(() {});
      },
      onCameraIdle: () {
        print("onCameraIdle");
      },
    );
    super.initState();
  }

  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 = LatLng(lat, long);
      setMap();
    } else {
      locationUtils = new LocationUtils(isShowConfirmDialog: true, context: context);
      locationUtils.getCurrentLocation(callBack: (value) {
        print(value);
        setMap();
      });
      // if (await PermissionService.isLocationEnabled()) {
      //   Geolocator.getLastKnownPosition().then((value) {
      //     latitude = value.latitude;
      //     longitude = value.longitude;
      //     currentPostion = 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 = LatLng(latitude, longitude);
      //         setMap();
      //       });
      //     });
      //   } else {
      //     Geolocator.getLastKnownPosition().then((value) {
      //       latitude = value.latitude;
      //       longitude = value.longitude;
      //       setMap();
      //     });
      //   }
      // }
    }
  }

  setLatitudeAndLongitude({bool isSetState = false, String latLong}) {
    if (latLong == null) {
      if (widget.model.addressesList.isEmpty) {
        setState(() {
          showCurrentLocation = true;
        });
      } else {
        latLong = widget.model.addressesList[widget.model.addressesList.length - 1].latLong;
      }
    }

    if (!showCurrentLocation) {
      List latLongArr = latLong.split(',');

      latitude = double.parse(latLongArr[0]);
      longitude = double.parse(latLongArr[1]);
      currentPostion = LatLng(latitude, longitude);
      setMap();
    }
  }

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

  @override
  Widget build(BuildContext context) {
    return AppScaffold(
      isShowDecPage: false,
      showNewAppBarTitle: true,
      showNewAppBar: true,
      appBarTitle: TranslationBase.of(context).homeHealthCare,
      body: Column(
        children: [
          if (widget.model.addressesList.isNotEmpty)
            Container(
              margin: EdgeInsets.only(left: 12, right: 12, bottom: 12, top: 12),
              decoration: cardRadius(12),
              child: Container(
                child: InkWell(
                  onTap: () => confirmSelectLocationDialog(widget.model.addressesList),
                  child: Container(
                    padding: EdgeInsets.all(8),
                    width: double.infinity,
                    // height: 65,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(10),
                      color: Colors.white,
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Expanded(
                          child: Text(
                            getAddressName(),
                            style: TextStyle(
                              fontWeight: FontWeight.w600,
                              fontSize: 12,
                              letterSpacing: -0.45,
                            ),
                          ),
                        ),
                        Icon(Icons.arrow_drop_down)
                      ],
                    ),
                  ),
                ),
                height: 50,
                width: double.infinity,
              ),
            ),
          InkWell(
            onTap: () {
              Navigator.push(
                context,
                FadePage(
                  page: LocationPage(
                    // latitude: latitude,
                    // longitude: longitude,
                  ),
                ),
              ).then((value) async {
                print(value);
                await widget.model.getCustomerAddresses();
                setState(() {});
              });
            },
            child: Padding(
              padding: EdgeInsets.only(left: 12, right: 12, bottom: 16, top: 8),
              child: Row(
                children: [
                  Icon(Icons.add_circle_outline_sharp),
                  mWidth(12),
                  Text(
                    TranslationBase.of(context).addNewAddress,
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                      letterSpacing: -0.46,
                    ),
                  ),
                ],
              ),
            ),
          ),
          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,
                  ),
                ),
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(left: 20, right: 20, top: 14, bottom: 14),
            child: DefaultButton(
              TranslationBase.of(context).continues,
              () {
                setState(() {
                  widget.patientERInsertPresOrderRequestModel.latitude = latitude;
                  widget.patientERInsertPresOrderRequestModel.longitude = longitude;
                });

                navigateTo(
                  context,
                  NewHomeHealthCareStepThreePage(
                    patientERInsertPresOrderRequestModel: widget.patientERInsertPresOrderRequestModel,
                    model: widget.model,
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }

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

  void confirmSelectLocationDialog(List<AddressInfo> addresses) {
    showDialog(
      context: context,
      builder: (cxt) => SelectLocationDialog(
        addresses: addresses,
        selectedAddress: _selectedAddress,
        onValueSelected: (value) {
          setLatitudeAndLongitude(latLong: value.latLong);
          setState(() {
            _selectedAddress = value;
          });
        },
      ),
    );
  }

  String getAddressName() {
    if (_selectedAddress != null)
      return _selectedAddress.address1;
    else
      return TranslationBase.of(context).selectAddress;
  }

  goToCurrentLocation() {
    Geolocator.getCurrentPosition().then((value) {
      _selectedAddress = AddressInfo(latLong: '${value.latitude},${value.longitude}');
      moveToLocation(LatLng(value.latitude, value.longitude));
    });
  }

  moveToLocation(LatLng location, {bool animate = true}) async {
    await Future.delayed(Duration(milliseconds: 200));
    _kGooglePlex = CameraPosition(
      target: location,
      zoom: 16.4746,
    );
    if (animate)
      (await mapController.future).animateCamera(
        CameraUpdate.newCameraPosition(_kGooglePlex),
      );
    else
      (await mapController.future).moveCamera(
        CameraUpdate.newCameraPosition(_kGooglePlex),
      );
  }
}
