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

import 'package:diplomaticquarterapp/config/config.dart';
import 'package:diplomaticquarterapp/core/model/prescriptions/Prescriptions.dart';
import 'package:diplomaticquarterapp/core/model/prescriptions/prescription_report.dart';
import 'package:diplomaticquarterapp/core/model/prescriptions/prescription_report_enh.dart';
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/medical/PrescriptionDeliveryViewModel.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/pages/AlHabibMedicalService/HomeHealthCare/NewHomeHealthCare/location_page.dart';
import 'package:diplomaticquarterapp/pages/AlHabibMedicalService/h2o/h20_setting.dart';
import 'package:diplomaticquarterapp/pages/base/base_view.dart';
import 'package:diplomaticquarterapp/services/permission/permission_service.dart';
import 'package:diplomaticquarterapp/theme/colors.dart';
import 'package:diplomaticquarterapp/uitl/location_util.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/buttons/defaultButton.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/radio_selection_dialog.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:provider/provider.dart';

import 'PrescriptionOrderOverveiw.dart';

class PrescriptionDeliveryAddressPage extends StatefulWidget {
  final Prescriptions prescriptions;
  final List<PrescriptionReport> prescriptionReportList;
  final List<PrescriptionReportEnh> prescriptionReportEnhList;

  const PrescriptionDeliveryAddressPage({Key key, this.prescriptions, this.prescriptionReportList, this.prescriptionReportEnhList}) : super(key: key);

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

class _PrescriptionDeliveryAddressPageState extends State<PrescriptionDeliveryAddressPage> {
  AddressInfo _selectedAddress;
  int _selectedAddressIndex = -1;
  Completer<GoogleMapController> _controller = Completer();
  ProjectViewModel projectViewModel;
  LocationUtils locationUtils;

  CameraPosition _kGooglePlex = CameraPosition(
    target: LatLng(24.665011045779107, 46.73502189439707),
    zoom: 14.4746,
  );
  Set<Marker> markers = new Set();
  double latitude = 0;
  double longitude = 0;

  @override
  void initState() {
    super.initState();
    locationUtils = new LocationUtils(isShowConfirmDialog: true, context: context);
    WidgetsBinding.instance.addPostFrameCallback((_) => locationUtils.getCurrentLocation());
  }

  // _getCurrentLocation() async {
  //   if (await PermissionService.isLocationEnabled()) {
  //     await Geolocator.getLastKnownPosition().then((value) {
  //       latitude = value.latitude;
  //       longitude = value.longitude;
  //       _kGooglePlex = CameraPosition(
  //         target: LatLng(latitude, longitude),
  //         zoom: 14.4746,
  //       );
  //     }).catchError((e) {
  //       latitude = 24.665011045779107;
  //       longitude = 46.73502189439707;
  //     });
  //   } else {
  //     if (Platform.isAndroid) {
  //       Utils.showPermissionConsentDialog(AppGlobal.context, TranslationBase.of(AppGlobal.context).locationPermissionDialog, () {
  //         Geolocator.getLastKnownPosition().then((value) {
  //           latitude = value.latitude;
  //           latitude = value.longitude;
  //           _kGooglePlex = CameraPosition(
  //             target: LatLng(latitude, longitude),
  //             zoom: 14.4746,
  //           );
  //         }).catchError((e) {
  //           latitude = 24.665011045779107;
  //           latitude = 46.73502189439707;
  //         });
  //       });
  //     } else {
  //       await Geolocator.getLastKnownPosition().then((value) {
  //         latitude = value.latitude;
  //         latitude = value.longitude;
  //         _kGooglePlex = CameraPosition(
  //           target: LatLng(latitude, longitude),
  //           zoom: 14.4746,
  //         );
  //       }).catchError((e) {
  //         latitude = 24.665011045779107;
  //         latitude = 46.73502189439707;
  //       });
  //     }
  //   }
  // }

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);
    return BaseView<PrescriptionDeliveryViewModel>(
      onModelReady: (model) => model.getCustomerInfo(),
      builder: (_, model, w) => AppScaffold(
        isShowAppBar: true,
        appBarTitle: TranslationBase.of(context).shippingAddresss,
        baseViewModel: model,
        showNewAppBarTitle: true,
        showNewAppBar: true,
        backgroundColor: CustomColors.appBackgroudGrey2Color,
        body: Container(
          child: Column(
            children: [
              Expanded(
                child: SingleChildScrollView(
                  padding: EdgeInsets.all(21),
                  physics: BouncingScrollPhysics(),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      CommonDropDownView(TranslationBase.of(context).selectAddress, getAddressName(), () {
                        List<RadioSelectionDialogModel> list = [
                          for (int i = 0; i < model.addressesList.length; i++) RadioSelectionDialogModel(model.addressesList[i].address1, i),
                        ];

                        showDialog(
                          context: context,
                          builder: (cxt) => RadioSelectionDialog(
                            listData: list,
                            isScrollable: true,
                            selectedIndex: _selectedAddressIndex,
                            onValueSelected: (index) {
                              _selectedAddressIndex = index;
                              _selectedAddress = model.addressesList[index];
                              List latLongArr = _selectedAddress.latLong.split(',');

                              latitude = double.parse(latLongArr[0]);
                              longitude = double.parse(latLongArr[1]);
                              markers = Set();
                              markers.add(
                                Marker(
                                  markerId: MarkerId(
                                    _selectedAddress.latLong.hashCode.toString(),
                                  ),
                                  position: LatLng(latitude, longitude),
                                ),
                              );
                              _kGooglePlex = CameraPosition(
                                target: LatLng(latitude, longitude),
                                zoom: 14.4746,
                              );
                              setState(() {});
                            },
                          ),
                        );
                      }).withBorderedContainer,
                      SizedBox(height: 12),
                      InkWell(
                        onTap: () async {
                          Navigator.push(
                            context,
                            FadePage(
                              page: LocationPage(
                                // latitude: latitude,
                                // longitude: longitude,
                              ),
                            ),
                          ).then((value) {
                            if (value != null && value is AddNewAddressRequestModel) {
                              setState(() {
                                _selectedAddress = AddressInfo(
                                  id: value.customer.id.toString(),
                                  email: value.customer.email,
                                  firstName: value.customer.addresses[0].firstName,
                                  lastName: value.customer.addresses[0].lastName,
                                  address1: value.customer.addresses[0].address1,
                                  address2: value.customer.addresses[0].address2,
                                  city: value.customer.addresses[0].city,
                                  country: value.customer.addresses[0].country,
                                  phoneNumber: value.customer.addresses[0].phoneNumber,
                                  latLong: value.customer.addresses[0].latLong,
                                  company: value.customer.addresses[0].company,
                                  countryId: value.customer.addresses[0].countryId,
                                  createdOnUtc: value.customer.addresses[0].createdOnUtc,
                                  customerAttributes: value.customer.addresses[0].customerAttributes,
                                  faxNumber: value.customer.addresses[0].faxNumber,
                                  province: value.customer.addresses[0].province,
                                  stateProvinceId: value.customer.addresses[0].stateProvinceId,
                                  zipPostalCode: value.customer.addresses[0].zipPostalCode,
                                );
                                List latLongArr = _selectedAddress.latLong.split(',');

                                latitude = double.parse(latLongArr[0]);
                                longitude = double.parse(latLongArr[1]);
                                markers = Set();
                                markers.add(
                                  Marker(
                                    markerId: MarkerId(
                                      _selectedAddress.latLong.hashCode.toString(),
                                    ),
                                    position: LatLng(latitude, longitude),
                                  ),
                                );
                                _kGooglePlex = CameraPosition(
                                  target: LatLng(latitude, longitude),
                                  zoom: 14.4746,
                                );
                              });
                            }
                          });
                        },
                        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,
                              ),
                            ),
                          ],
                        ),
                      ),
                      SizedBox(height: 12),
                      if (_selectedAddress != null)
                        Container(
                          decoration: cardRadius(15),
                          padding: const EdgeInsets.all(12.0),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                TranslationBase.of(context).selectAddress + ":",
                                style: TextStyle(fontSize: 14, color: Color(0xff575757), fontWeight: FontWeight.w600, letterSpacing: -0.56),
                              ),
                              mHeight(12),
                              Container(
                                height: 175,
                                decoration: containerColorRadiusBorder(Colors.white, 12, Color(0xffDDDDDD)),
                                clipBehavior: Clip.antiAlias,
                                child: Container(
                                  decoration: cardRadius(10),
                                  clipBehavior: Clip.antiAlias,
                                  margin: const EdgeInsets.all(0),
                                  child: Image.network(
                                    "https://maps.googleapis.com/maps/api/staticmap?center=" +
                                        _kGooglePlex.target.latitude.toString() +
                                        "," +
                                        _kGooglePlex.target.longitude.toString() +
                                        "&zoom=16&size=600x300&maptype=roadmap&markers=color:red%7C" +
                                        _kGooglePlex.target.latitude.toString() +
                                        "," +
                                        _kGooglePlex.target.longitude.toString() +
                                        "&key=AIzaSyCyDbWUM9d_sBUGIE8PcuShzPaqO08NSC8",
                                    width: double.infinity,
                                    height: double.infinity,
                                    fit: BoxFit.cover,
                                  ),
                                ),
                              ),
                              SizedBox(height: 18),
                              Text(
                                TranslationBase.of(context).shippingAddresss + ":",
                                style: TextStyle(fontSize: 14, color: Color(0xff575757), fontWeight: FontWeight.w600, letterSpacing: -0.56),
                              ),
                              SizedBox(height: 2),
                              Text(
                                '${model.user.firstName} ${model.user.lastName}',
                                style: TextStyle(fontSize: 12, color: Color(0xff2B353E), fontWeight: FontWeight.w600, letterSpacing: -0.48),
                              ),
                              Text(
                                _selectedAddress.address1,
                                style: TextStyle(fontSize: 12, color: Color(0xff2B353E), fontWeight: FontWeight.w600, letterSpacing: -0.48),
                              ),
                              Text(
                                _selectedAddress.address2,
                                style: TextStyle(fontSize: 12, color: Color(0xff2B353E), fontWeight: FontWeight.w600, letterSpacing: -0.48),
                              ),
                              Text(
                                _selectedAddress.city + " " + _selectedAddress.country,
                                style: TextStyle(fontSize: 12, color: Color(0xff2B353E), fontWeight: FontWeight.w600, letterSpacing: -0.48),
                              ),
                            ],
                          ),
                        )
                    ],
                  ),
                ),
              ),
              DefaultButton(
                TranslationBase.of(context).continues.toUpperCase(),
                _selectedAddress == null
                    ? null
                    : () {
                        Navigator.push(
                          context,
                          FadePage(
                            page: PrescriptionOrderOverview(
                              latitude: latitude,
                              longitude: longitude,
                              prescriptionReportEnhList: widget.prescriptionReportEnhList,
                              prescriptionReportList: widget.prescriptionReportList,
                              prescriptions: widget.prescriptions,
                              selectedAddress: _selectedAddress,
                            ),
                          ),
                        );
                      },
                disabledColor: CustomColors.grey2,
              ).insideContainer,
            ],
          ),
        ),
      ),
    );
  }

  void confirmSelectLocationDialog(
    List<AddressInfo> addresses,
  ) {
    showDialog(
      context: context,
      builder: (cxt) => SelectLocationDialog(
        addresses: addresses,
        selectedAddress: _selectedAddress,
        onValueSelected: (value) {
          setState(() {
            _selectedAddress = value;
            List latLongArr = value.latLong.split(',');

            latitude = double.parse(latLongArr[0]);
            longitude = double.parse(latLongArr[1]);
            markers = Set();
            markers.add(
              Marker(
                markerId: MarkerId(
                  _selectedAddress.latLong.hashCode.toString(),
                ),
                position: LatLng(latitude, longitude),
              ),
            );
            _kGooglePlex = CameraPosition(
              target: LatLng(latitude, longitude),
              zoom: 14.4746,
            );
          });
        },
      ),
    );
  }

  String getAddressName() {
    return _selectedAddress?.address1 ?? "";
  }
}
