import 'package:diplomaticquarterapp/core/model/pharmacies/Addresses.dart';
import 'package:diplomaticquarterapp/core/viewModels/pharmacyModule/PharmacyAddressesViewModel.dart';
import 'package:diplomaticquarterapp/pages/base/base_view.dart';
import 'package:diplomaticquarterapp/widgets/buttons/borderedButton.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/pickupLocation/PickupLocationFromMap.dart';
import 'package:flutter/material.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_place_picker/google_maps_place_picker.dart';

class AddAddressPage extends StatefulWidget {
  final Addresses editedAddress;
  final Function(PickResult) onPick;

  AddAddressPage(this.editedAddress, this.onPick);

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

class _AddAddressPageState extends State<AddAddressPage> {
  double _latitude;
  double _longitude;

  @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();
    }
  }

  _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;

    return BaseView<PharmacyAddressesViewModel>(
      builder: (_, model, wi) => AppScaffold(
        appBarTitle: TranslationBase.of(context).changeAddress,
        isShowAppBar: true,
        isPharmacy: true,
        backgroundColor: Colors.white,
        body: Container(
          height: height * 1,
          child: PickupLocationFromMap(
            latitude: _latitude,
            longitude: _longitude,
            isWithAppBar: false,
            buttonColor: Color(0xFF5AB145),
            buttonLabel: TranslationBase.of(context).save,
            onPick: (value) {
              widget.onPick(value);
            },
          ),
        ),
      ),
    );
  }
}
