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/ComprehensiveMedicalCheckup/NewCMC/cmc_location_page.dart';
import 'package:diplomaticquarterapp/pages/AlHabibMedicalService/HomeHealthCare/NewHomeHealthCare/location_page.dart';
import 'package:diplomaticquarterapp/pages/base/base_view.dart';
import 'package:diplomaticquarterapp/theme/colors.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/uitl/utils_new.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,
        showNewAppBarTitle: true,
        showNewAppBar: true,
        backgroundColor: CustomColors.appBackgroudGrey2Color,
        body: Container(
          child: Column(
            children: [
              Expanded(
                child: SingleChildScrollView(
                  physics: BouncingScrollPhysics(),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Container(
                        margin: EdgeInsets.only(left: 12, right: 12, bottom: 12, top: 12),
                        decoration: cardRadius(12),
                        child: Container(
                          child: InkWell(
                            onTap: () => confirmSelectLocationDialog(model.addressesList),
                            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,
                            )),
                          ).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: 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,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                      if (_selectedAddress != null)
                        Container(
                          decoration: cardRadius(12),
                          margin: EdgeInsets.all(12),
                          child: Padding(
                            padding: const EdgeInsets.all(12.0),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Texts(
                                  TranslationBase.of(context).selectAddress + ":",
                                  fontSize: 12,
                                  color: CustomColors.grey,
                                  fontWeight: FontWeight.w600,
                                ),
                                mHeight(12),
                                Container(
                                  height: 175,
                                  decoration: containerColorRadiusBorder(Colors.white, 12, Colors.grey),
                                  clipBehavior: Clip.antiAlias,
                                  child: Container(
                                    decoration: cardRadius(12),
                                    clipBehavior: Clip.antiAlias,
                                    margin: const EdgeInsets.all(0),
                                    // child: GoogleMap(
                                    //   mapType: MapType.normal,
                                    //   markers: markers,
                                    //   initialCameraPosition: _kGooglePlex,
                                    //   onMapCreated: (GoogleMapController controller) {
                                    //     _controller.complete(controller);
                                    //   },
                                    // ),
                                    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: 10,
                                ),
                                Texts(
                                  TranslationBase.of(context).shippingAddresss + ":",
                                  fontSize: 12,
                                  color: CustomColors.grey,
                                  fontWeight: FontWeight.w600,
                                ),
                                SizedBox(
                                  height: 2,
                                ),
                                Texts(
                                  '${model.user.firstName} ${model.user.lastName}',
                                  fontSize: 12,
                                  fontWeight: FontWeight.w600,
                                ),
                                Texts(
                                  _selectedAddress.address1,
                                  fontSize: 12,
                                  fontWeight: FontWeight.w600,
                                ),
                                Texts(
                                  _selectedAddress.address2,
                                  fontSize: 12,
                                  fontWeight: FontWeight.w600,
                                ),
                                Texts(
                                  _selectedAddress.city + " " + _selectedAddress.country,
                                  fontSize: 12,
                                  fontWeight: FontWeight.w600,
                                ),
                              ],
                            ),
                          ),
                        )
                    ],
                  ),
                ),
              ),
              Container(
                decoration: cardRadius(0),
                margin: EdgeInsets.zero,
                child: Container(
                  width: double.infinity,
                  padding: EdgeInsets.only(left: 16, right: 16, top: 16),
                  child: Button(
                    label: TranslationBase.of(context).continues.toUpperCase(),
                    disabled: _selectedAddress == null,
                    backgroundColor: _selectedAddress == null ? CustomColors.grey2 : CustomColors.accentColor,
                    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;
  }
}
