import 'package:diplomaticquarterapp/config/config.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/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/select_location_dialog.dart';
import 'package:diplomaticquarterapp/widgets/buttons/secondary_button.dart';
import 'package:diplomaticquarterapp/widgets/data_display/text.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:google_maps_flutter/google_maps_flutter.dart';
import 'package:google_maps_place_picker/google_maps_place_picker.dart';
import 'package:provider/provider.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;


  @override
  void initState() {
    if (widget.patientERInsertPresOrderRequestModel.latitude == null) {
      setLatitudeAndLongitude();
    } else {
      latitude = widget.patientERInsertPresOrderRequestModel.latitude;
      longitude = widget.patientERInsertPresOrderRequestModel.longitude;
    }

    super.initState();
  }

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

  }

  @override
  Widget build(BuildContext context) {
    ProjectViewModel projectViewModel = Provider.of(context);
    return AppScaffold(
      isShowDecPage: false,
      body: Stack(
        children: [
          PlacePicker(
            apiKey: GOOGLE_API_KEY,
            enableMyLocationButton: true,
            automaticallyImplyAppBarLeading: false,
            autocompleteOnTrailingWhitespace: true,
            selectInitialPosition: true,
            autocompleteLanguage: projectViewModel.currentLanguage,
            enableMapTypeButton: true,
            searchForInitialValue: false,

            onPlacePicked: (PickResult result) {
              print(result.adrAddress);
              widget.changePageViewIndex(3);
            },
            selectedPlaceWidgetBuilder:
                (_, selectedPlace, state, isSearchBarFocused) {
              print("state: $state, isSearchBarFocused: $isSearchBarFocused");
              return isSearchBarFocused
                  ? Container()
                  : FloatingCard(
                bottomPosition: 0.0,
                leftPosition: 0.0,
                rightPosition: 0.0,
                width: 500,
                borderRadius: BorderRadius.circular(12.0),
                child: state == SearchingState.Searching
                    ? Center(child: CircularProgressIndicator())
                    : Container(
                  margin: EdgeInsets.all(12),
                  child: Column(
                    children: [
                      SecondaryButton(
                        color: Colors.grey[800],
                        textColor: Colors.white,
                        onTap: () {
                          Navigator.push(
                                        context,
                                        FadePage(
                                          page:
                                              LocationPage(
                                            latitude: latitude,
                                            longitude: longitude,
                                          ),
                                        ),
                                      );
                                    },
                        label: TranslationBase.of(context).addNewAddress,
                      ),
                      SizedBox(height: 10,),
                      SecondaryButton(
                        color: Colors.red[800],
                        textColor: Colors.white,
                        onTap: () {
                          setState(() {
                            widget.patientERInsertPresOrderRequestModel
                                .latitude =
                                selectedPlace.geometry.location.lat;
                            widget.patientERInsertPresOrderRequestModel
                                .longitude =
                                selectedPlace.geometry.location.lng;
                          });
                          widget.changePageViewIndex(3);
                        },
                        label: TranslationBase.of(context).confirm,
                      ),
                    ],
                  ),
                ),
              );
            },
            initialPosition: LatLng(latitude, longitude),
            useCurrentLocation: showCurrentLocation,
          ),
          if(widget.model.addressesList.isNotEmpty)
          Container(
            child: InkWell(
              onTap: () =>
                  confirmSelectLocationDialog(widget.model.addressesList),
              child: Container(
                padding: EdgeInsets.all(10),
                width: double.infinity,
                // height: 65,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10),
                    color: Colors.white),
                child: Row(
                  mainAxisAlignment:
                  MainAxisAlignment.spaceBetween,
                  children: [
                    Expanded(child: Texts(getAddressName(), fontSize: 14,),),
                    Icon(Icons.arrow_drop_down)
                  ],
                ),
              ),
            ),
            height: 56, width: double.infinity, color: Theme
              .of(context)
              .scaffoldBackgroundColor,

          )
        ],
      ),
    );
  }


  void confirmSelectLocationDialog(List<AddressInfo> addresses) {
    showDialog(
      context: context,
      child: 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;
  }
}
