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

import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/model/AlHabibMedicalService/ComprehensiveMedicalCheckup/cmc_insert_pres_order_request_model.dart';
import 'package:diplomaticquarterapp/core/model/ImagesInfo.dart';
import 'package:diplomaticquarterapp/core/service/AlHabibMedicalService/customer_addresses_service.dart';
import 'package:diplomaticquarterapp/core/viewModels/AlHabibMedicalService/cmc_view_model.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/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/secondary_button.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/select_location_dialog.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.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 'package:permission_handler/permission_handler.dart';

import 'cmc_location_page.dart';
import 'new_cmc_step_three_page.dart';

class NewCMCStepTowPage extends StatefulWidget {
  final Function(PickResult) onPick;
  final double latitude;
  final double longitude;
  final CMCInsertPresOrderRequestModel cmcInsertPresOrderRequestModel;
  final CMCViewModel model;

  const NewCMCStepTowPage({Key key, this.onPick, this.latitude, this.longitude, this.cmcInsertPresOrderRequestModel, this.model}) : super(key: key);

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

class _NewCMCStepTowPageState extends State<NewCMCStepTowPage> {
  double latitude = 0;
  double longitude = 0;
  AddressInfo _selectedAddress;
  bool showCurrentLocation = false;
  AppSharedPreferences sharedPref = AppSharedPreferences();

  static CameraPosition cameraPosition = CameraPosition(
    target: LatLng(37.42796133580664, -122.085749655962),
    zoom: 14.4746,
  );

  LatLng currentPostion;

  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 {
      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;
            currentPostion = LatLng(latitude, longitude);
            setMap();
          });
        }
      }
    }
  }

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

  setMap() {
    setState(() {
      cameraPosition = CameraPosition(
        target: currentPostion,
        zoom: 14.4746,
      );
      if (appMap != null) appMap.moveTo(cameraPostion: cameraPosition);
    });
  }

  Future<Map<Permission, PermissionStatus>> requestPermissions() async {
    var permissionResults = [
      Permission.location,
      Permission.locationAlways,
    ].request();

    return permissionResults;
  }

  setLatitudeAndLongitude({bool isSetState = false, String latLong}) async {
    print("latLong " + latLong.toString());
    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]);
      print("sssss1 " + latitude.toString());
      print("sssss2 " + longitude.toString());
      currentPostion = LatLng(latitude, longitude);
      setMap();
    }
  }

  AppMap appMap;

  @override
  Widget build(BuildContext context) {
    return AppScaffold(
      isShowAppBar: true,
      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).comprehensiveMedicalCheckup,
      showNewAppBar: true,
      showNewAppBarTitle: true,
      backgroundColor: CustomColors.appBackgroudGreyColor,
      baseViewModel: widget.model,
      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,
                    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: () async {
              bool isNeedToUpdate = false;
              await Navigator.of(context).push(new MaterialPageRoute<dynamic>(
                builder: (BuildContext context) {
                  return CMCLocationPage(
                    latitude: latitude,
                    longitude: longitude,
                    onPick: () {
                      isNeedToUpdate = true;
                    },
                  );
                },
              ));
              if (isNeedToUpdate) {
                _selectedAddress = new AddressInfo();
                _selectedAddress.address1 = widget.model.addressesList.last.address1;
                showCurrentLocation = false;
                setLatitudeAndLongitude();
                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,
                Icon(
                  Icons.place,
                  color: CustomColors.accentColor,
                  size: 50,
                ),
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(left: 20, right: 20, top: 14, bottom: 14),
            child: SecondaryButton(
              color: Colors.red[800],
              textColor: Colors.white,
              onTap: () {
                setState(() {
                  widget.cmcInsertPresOrderRequestModel.latitude = latitude;
                  widget.cmcInsertPresOrderRequestModel.longitude = longitude;
                });
                // widget.changePageViewIndex(3);
                navigateTo(
                  context,
                  NewCMCStepThreePage(
                    cmcInsertPresOrderRequestModel: widget.cmcInsertPresOrderRequestModel,
                    model: widget.model,
                  ),
                );
              },
              label: TranslationBase.of(context).continues,
            ),
          ),
        ],
      ),
    );
  }

  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) {
          showCurrentLocation = false;
          setLatitudeAndLongitude(latLong: value.latLong);

          setState(() {
            _selectedAddress = value;
          });
        },
      ),
    );
  }

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