import 'dart:async';

import 'package:diplomaticquarterapp/core/service/AlHabibMedicalService/customer_addresses_service.dart';
import 'package:diplomaticquarterapp/core/viewModels/AlHabibMedicalService/add_new_address_Request_Model.dart';
import 'package:diplomaticquarterapp/core/viewModels/pharmacyModule/PharmacyAddressesViewModel.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/pages/base/base_view.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:diplomaticquarterapp/widgets/pickupLocation/PickupLocationFromMap.dart';
import 'package:flutter/material.dart';
import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:google_maps_place_picker/google_maps_place_picker.dart';
import 'package:provider/provider.dart';

class AddAddressPage extends StatefulWidget {
  final AddressInfo editedAddress;
  final Function(Placemark, String) onPick;

  AddAddressPage(this.editedAddress, this.onPick);

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

class _AddAddressPageState extends State<AddAddressPage> {
  double _latitude;
  double _longitude;
  AppMap appMap;
  AppSharedPreferences sharedPref = AppSharedPreferences();
  LatLng currentPostion;
  Completer<GoogleMapController> mapController = Completer();
  Placemark selectedPlace;

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

  @override
  void initState() {
    super.initState();

    if (widget.editedAddress != null && widget.editedAddress.latLong != null && widget.editedAddress.latLong != "") {
      List<String> latLng = widget.editedAddress.latLong.split(",");
      _latitude = double.parse(latLng[0]);
      _longitude = double.parse(latLng[1]);
    } else {
      _getCurrentLocation();
    }
    // setState(() {});

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

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

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

  _getCurrentLocation() async {
    await Geolocator.getLastKnownPosition().then((value) {
      _latitude = value.latitude;
      _longitude = value.longitude;
    }).catchError((e) {
      _longitude = 0;
      _latitude = 0;
    });
  }

  @override
  Widget build(BuildContext context) {
    final mediaQuery = MediaQuery.of(context);
    final height = mediaQuery.size.height - 60 - mediaQuery.padding.top;
    ProjectViewModel projectViewModel = Provider.of(context);

    return BaseView<PharmacyAddressesViewModel>(
      builder: (_, model, wi) => AppScaffold(
        appBarTitle: TranslationBase.of(context).changeAddress,
        isShowAppBar: true,
        isPharmacy: true,
        backgroundColor: Colors.white,
        showNewAppBarTitle: true,
        showNewAppBar: true,
        body: 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.name,
                //         address2: selectedPlace.street,
                //         customerAttributes: "",
                //         city: selectedPlace.locality,
                //         createdOnUtc: "",
                //         id: "0",
                //         faxNumber: "",
                //         phoneNumber: projectViewModel.user.mobileNumber,
                //         province: selectedPlace.locality,
                //         countryId: 69,
                //         latLong: "$_latitude,$_longitude",
                //         country: selectedPlace.country,
                //         zipPostalCode: selectedPlace.postalCode,
                //         email: projectViewModel.user.emailAddress)
                //   ]),
                // );

                widget.onPick(selectedPlace, "$_latitude,$_longitude");
                Navigator.of(context).pop();

                // 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);
              }),
            ),
          ],
        ),

        // Container(
        //   height: height * 1,
        //   child: PickupLocationFromMap(
        //     latitude: _latitude ?? 0,
        //     longitude: _longitude ?? 0,
        //     isWithAppBar: false,
        //     buttonColor: Color(0xFF5AB145),
        //     buttonLabel: TranslationBase.of(context).save,
        //     onPick: (value) {
        //       widget.onPick(value);
        //     },
        //   ),
        ),
      );
    // );
  }
}
