import 'dart:async';

import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/service/AlHabibMedicalService/customer_addresses_service.dart';
import 'package:diplomaticquarterapp/core/viewModels/er/rrt-view-model.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/models/rrt/service_price.dart';
import 'package:diplomaticquarterapp/pages/AlHabibMedicalService/HomeHealthCare/NewHomeHealthCare/location_page.dart';
import 'package:diplomaticquarterapp/pages/BookAppointment/widgets/reminder_dialog.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/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:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';

import 'rrt-place-order.dart';

class RRTRequestPickupAddressPage extends StatefulWidget {
  final ServicePrice servicePrice;

  RRTRequestPickupAddressPage({@required this.servicePrice});

  @override
  State<StatefulWidget> createState() => RRTRequestPickupAddressPageState();
}

class RRTRequestPickupAddressPageState extends State<RRTRequestPickupAddressPage> with SingleTickerProviderStateMixin {
  bool acceptTerms = false;

  bool mapIdle = true;
  Completer<GoogleMapController> mapController = Completer();

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

  LatLng currentPostion;
  List<AddressInfo> myAddresses = [];
  AddressInfo selectedAddress = new AddressInfo();
  StreamController<int> addressStreamController = StreamController();
  Stream<int> addressStream;
  StreamController<int> addressLoadingStreamController = StreamController();
  Stream<int> addressLoadingStream;

  // AddressInfo _selectedAddress;
  double latitude = 0;
  double longitude = 0;
  AppMap appMap;
  bool showCurrentLocation = false;
  AppSharedPreferences sharedPref = AppSharedPreferences();

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

    appMap = AppMap(
      cameraPosition.toMap(),
      onCameraMove: (camera) {
        _updatePosition(camera);
      },
      onMapCreated: () {
        _getUserLocation();
        setState(() {});
      },
    );

    // addressStream = addressStreamController.stream;
    // addressLoadingStream = addressLoadingStreamController.stream;
  }

  setLatitudeAndLongitude({bool isSetState = false, String latLong}) async {
    if (latLong == null) {
      if (myAddresses.isEmpty) {
        setState(() {
          showCurrentLocation = true;
        });
      } else {
        latLong = myAddresses[myAddresses.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(() {
      cameraPosition = CameraPosition(
        target: currentPostion,
        zoom: 16,
      );
      appMap.moveTo(cameraPostion: cameraPosition);
      selectedAddress.latLong = currentPostion.latitude.toString() + "," + currentPostion.longitude.toString();
    });
  }

  void loadAddresses() async {
    await viewModel.getCustomerInfo();

    if (viewModel.addressesList.isNotEmpty) setState(() {});
  }

  TranslationBase localize;
  RRTViewModel viewModel;

  @override
  Widget build(BuildContext context) {
    localize = TranslationBase.of(context);
    ProjectViewModel projectViewModel = Provider.of(context);

    addressStreamController.sink.add(0);

    return BaseView<RRTViewModel>(
        onModelReady: (vm) {
          viewModel = vm;
          loadAddresses();
          myAddresses = viewModel.addressesList;
        },
        builder: (ctx, vm, widget) => AppScaffold(
            appBarTitle: localize.pickupLocation,
            isShowAppBar: true,
            showNewAppBar: true,
            showNewAppBarTitle: true,
            baseViewModel: viewModel,
            body: Column(
              children: [
                Container(
                  margin: EdgeInsets.only(left: 12, right: 12, bottom: 12, top: 12),
                  decoration: cardRadius(12),

                  child: Container(
                    child: InkWell(
                      onTap: () => confirmSelectLocationDialog(myAddresses),
                      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: () async {
                    Navigator.push(
                      context,
                      FadePage(
                        page: LocationPage(
                          latitude: latitude,
                          longitude: longitude,
                        ),
                      ),
                    );
                  },
                  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: continueButton(),
                ),
              ],
            )));
  }

  void _updatePosition(CameraPosition _position) {
    latitude = _position.target.latitude;
    longitude = _position.target.longitude;
    selectedAddress.latLong = latitude.toString() + "," + longitude.toString();
  }

  Widget centerTargetPoint() {
    double size = mapIdle ? 20 : 30;
    double margin = mapIdle ? 3 : 10;
    return Center(
      child: Container(
        width: size,
        height: size,
        decoration: BoxDecoration(borderRadius: BorderRadius.circular(20), border: Border.all(width: 2, color: Theme.of(context).appBarTheme.color)),
        child: Container(margin: EdgeInsets.all(margin), decoration: BoxDecoration(color: Theme.of(context).appBarTheme.color, borderRadius: BorderRadius.circular(20))),
      ),
    );
  }

  Widget continueButton() {
    return Padding(
      padding: const EdgeInsets.all(0.0),
      child: DefaultButton(TranslationBase.of(context).continues, () {
        Navigator.push(
            context,
            FadePage(
                page: RRTPlaceOrderPage(
              selectedAddress: selectedAddress,
              servicePrice: widget.servicePrice,
            )));
      }),
    );
  }

  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 && selectedAddress.address1 != null)
      return selectedAddress.address1;
    else
      return TranslationBase.of(context).selectAddress;
  }

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

  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 Permission.location.request().isGranted) {
        var position = await GeolocatorPlatform.instance.getCurrentPosition(desiredAccuracy: LocationAccuracy.low);
        currentPostion = LatLng(position.latitude, position.longitude);
        latitude = position.latitude;
        longitude = position.longitude;
        setMap();
      } else {
        requestPermissions().then(
          (value) async {
            if (value[Permission.location].isGranted) {
              var position = await GeolocatorPlatform.instance.getCurrentPosition(desiredAccuracy: LocationAccuracy.low);
              currentPostion = LatLng(position.latitude, position.longitude);
              latitude = position.latitude;
              longitude = position.longitude;
              setMap();
            }
          },
        );
      }
    }
  }

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