import 'dart:async';

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/base/base_view.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/buttons/button.dart';
import 'package:diplomaticquarterapp/widgets/data_display/text.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;
  Completer<GoogleMapController> _controller = Completer();

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

  _getCurrentLocation() async {
    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 projectViewModel = Provider.of(context);
    return BaseView<PrescriptionDeliveryViewModel>(
      onModelReady: (model) => model.getCustomerInfo(),
      builder: (_, model, w) => AppScaffold(
          isShowAppBar: true,
          appBarTitle: TranslationBase.of(context).shippingAddresss,
          baseViewModel: model,
          body: Container(
            height: MediaQuery.of(context).size.height * 0.65,
            child: SingleChildScrollView(
              physics: BouncingScrollPhysics(),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  SizedBox(
                    height: 8,
                  ),
                  InkWell(
                    onTap: () {
                      confirmSelectLocationDialog(model.addressesList);
                    },
                    child: Container(
                      margin: EdgeInsets.only(left: 10, right: 10, top: 15),
                      height: 50,
                      decoration: BoxDecoration(
                        border: Border.all(color: Colors.grey),
                        borderRadius: BorderRadius.circular(7),
                        color: Colors.white,
                        shape: BoxShape.rectangle,
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Expanded(
                            child: Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: Container(
                                child: Text(
                                  getAddressName(),
                                ),
                                margin: EdgeInsets.only(left: 10, right: 10),
                              ),
                            ),
                          ),
                          Icon(
                            Icons.arrow_drop_down,
                            size: 22,
                            color: Colors.grey,
                          )
                        ],
                      ),
                    ),
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  _selectedAddress == null
                      ? Container(
                          child: Image.asset(
                            projectViewModel.isArabic
                                ? 'assets/images/pharmacy/shipping_image_ar.png'
                                : 'assets/images/pharmacy/shipping_image.png',
                            height: 300,
                          ),
                        )
                      : Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Padding(
                                padding: const EdgeInsets.all(8.0),
                                child: Container(
                                  decoration: BoxDecoration(
                                      border: Border.all(color: Colors.grey)),
                                  height: 200,
                                  child: GoogleMap(
                                    mapType: MapType.normal,
                                    markers: markers,
                                    initialCameraPosition: _kGooglePlex,
                                    onMapCreated:
                                        (GoogleMapController controller) {
                                      _controller.complete(controller);
                                    },
                                  ),
                                ),
                              ),
                              SizedBox(
                                height: 10,
                              ),
                              Texts(
                                  TranslationBase.of(context).shippingAddresss),
                              SizedBox(
                                height: 10,
                              ),
                              Texts(
                                  '${model.user.firstName} ${model.user.lastName}'),
                              SizedBox(
                                height: 10,
                              ),
                              Texts(_selectedAddress.address1),
                              SizedBox(
                                height: 10,
                              ),
                              Texts(_selectedAddress.address2),
                              SizedBox(
                                height: 10,
                              ),
                              Texts(_selectedAddress.city +
                                  " " +
                                  _selectedAddress.country),
                            ],
                          ),
                        )
                ],
              ),
            ),
          ),
          bottomSheet: Container(
            width: double.infinity,
            height: MediaQuery.of(context).size.height * 0.25,
            color: Colors.grey[100],
            child: Column(
              children: <Widget>[
                Divider(),
                Container(
                  width: MediaQuery.of(context).size.width * 0.8,
                  child: Button(
                    label:
                        TranslationBase.of(context).addNewAddress.toUpperCase(),
                    onTap: () {
                      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,
                           );
                         });
                        }
                      });
                    },
                  ),
                ),
                Container(
                    width: MediaQuery.of(context).size.width * 0.8,
                    child: Button(
                      label:
                          TranslationBase.of(context).continues.toUpperCase(),
                      disabled: _selectedAddress == null,
                      backgroundColor: _selectedAddress == null
                          ? Colors.green[300]
                          : Colors.green[700],
                      onTap: () {
                        Navigator.push(
                          context,
                          FadePage(
                            page: PrescriptionOrderOverview(
                              latitude: latitude,
                              longitude: longitude,
                              prescriptionReportEnhList:
                                  widget.prescriptionReportEnhList,
                              prescriptionReportList:
                                  widget.prescriptionReportList,
                              prescriptions: widget.prescriptions,
                              selectedAddress: _selectedAddress,
                            ),
                          ),
                        );
                      },
                    ))
              ],
            ),
          )),
    );
  }

  void confirmSelectLocationDialog(
    List<AddressInfo> addresses,
  ) {
    showDialog(
      context: context,
      child: 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() {
    if (_selectedAddress != null)
      return _selectedAddress.address1;
    else
      return TranslationBase.of(context).selectAddress;
  }
}
