import 'package:diplomaticquarterapp/core/enum/viewstate.dart';
import 'package:diplomaticquarterapp/core/model/er/PatientER.dart';
import 'package:diplomaticquarterapp/core/model/er/PatientER_RC.dart';
import 'package:diplomaticquarterapp/core/model/hospitals/hospitals_model.dart';
import 'package:diplomaticquarterapp/core/viewModels/er/am_request_view_model.dart';
import 'package:diplomaticquarterapp/models/Appointments/AppoimentAllHistoryResultList.dart';
import 'package:diplomaticquarterapp/pages/ErService/widgets/AppointmentCard.dart';
import 'package:diplomaticquarterapp/uitl/ProgressDialog.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/date_uitl.dart';
import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart';
import 'package:diplomaticquarterapp/widgets/data_display/text.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/radio_selection_dialog.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/pickupLocation/PickupLocationFromMap.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_place_picker/google_maps_place_picker.dart';

import '../AvailableAppointmentsPage.dart';

enum HaveAppointment { YES, NO }

class PickupLocation extends StatefulWidget {
  final Function changeCurrentTab;
  final PatientER patientER;
  final PatientER_RC patientER_RC;
  final AmRequestViewModel amRequestViewModel;

  PickupLocation({Key key, this.changeCurrentTab, this.patientER, this.patientER_RC, this.amRequestViewModel});

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

class _PickupLocationState extends State<PickupLocation> {
  bool _isInsideHome = false;
  HaveAppointment _haveAppointment = HaveAppointment.NO;
  double _latitude;
  double _longitude;
  AppoitmentAllHistoryResultList myAppointment;
  HospitalsModel _selectedHospital;
  PickResult _result;

  @override
  void initState() {
    super.initState();
    _getCurrentLocation();
    setState(() {});
  }

  _getCurrentLocation() async {
    await Geolocator.getLastKnownPosition().then((value) {
      _latitude = value.latitude;
      _longitude = value.longitude;
    }).catchError((e) {
      _longitude = 0;
      _latitude = 0;
    });
  }

  @override
  Widget build(BuildContext context) {
    return AppScaffold(
      isShowAppBar: false,
      isShowDecPage: false,
      body: SingleChildScrollView(
        physics: BouncingScrollPhysics(),
        child: Container(
          margin: EdgeInsets.only(left: 12, right: 12, top: 12),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              if (widget.patientER_RC.transportationDetails.direction == 1)
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(TranslationBase.of(context).pickupLocation, style: TextStyle(fontSize: 16.0, letterSpacing: -0.64, fontWeight: FontWeight.w600)),
                    SizedBox(
                      height: 15,
                    ),
                    Container(
                      padding: EdgeInsets.only(left: 16, right: 16, bottom: 15, top: 15),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(15),
                        color: Colors.white,
                        border: Border.all(
                          color: Color(0xffefefef),
                          width: 1,
                        ),
                      ),
                      child: InkWell(
                        onTap: () {
                          Navigator.push(
                            context,
                            FadePage(
                                page: PickupLocationFromMap(
                              latitude: _latitude ?? 0,
                              longitude: _longitude ?? 0,
                              onPick: (value) {
                                setState(() {
                                  _result = value;
                                });
                              },
                            )),
                          );
                        },
                        child: Row(
                          children: [
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    TranslationBase.of(context).selectMap,
                                    style: TextStyle(
                                      fontSize: 11,
                                      fontWeight: FontWeight.w600,
                                      color: Color(0xff2B353E),
                                      letterSpacing: -0.44,
                                    ),
                                  ),
                                  Text(
                                    getSelectFromMapName(context),
                                    style: TextStyle(
                                      fontSize: 14,
                                      height: 21 / 14,
                                      fontWeight: FontWeight.w400,
                                      color: Color(0xff2B353E),
                                      letterSpacing: -0.44,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            Icon(Icons.arrow_drop_down),
                          ],
                        ),
                      ),
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    Text(TranslationBase.of(context).pickupSpot, style: TextStyle(fontSize: 16.0, letterSpacing: -0.64, fontWeight: FontWeight.w600)),
                    SizedBox(
                      height: 5,
                    ),
                    InkWell(
                      onTap: () {
                        setState(() {
                          _isInsideHome = !_isInsideHome;
                        });
                      },
                      child: Container(
                        child: ListTile(
                          contentPadding: EdgeInsets.only(left: 0.0, right: 0.0),
                          title: Row(
                            children: [
                              Checkbox(
                                value: _isInsideHome,
                                onChanged: (value) {
                                  setState(() {
                                    _isInsideHome = value;
                                  });
                                },
                              ),
                              Text(
                                TranslationBase.of(context).insideHome,
                                style: TextStyle(
                                  fontSize: 12.0,
                                  letterSpacing: -0.48,
                                  fontWeight: FontWeight.w600,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    Text(TranslationBase.of(context).haveAppo, style: TextStyle(fontSize: 16.0, letterSpacing: -0.64, fontWeight: FontWeight.w600)),
                    SizedBox(
                      height: 5,
                    ),
                    Row(
                      children: [
                        Expanded(
                          child: InkWell(
                            onTap: () {
                              if (myAppointment == null) {
                                getAppointment();
                                setState(() {
                                  _haveAppointment = HaveAppointment.YES;
                                });
                              }
                            },
                            child: Container(
                              child: ListTile(
                                contentPadding: EdgeInsets.only(left: 0.0, right: 0.0),
                                title: Row(
                                  children: [
                                    Radio(
                                      value: HaveAppointment.YES,
                                      groupValue: _haveAppointment,
                                      onChanged: (value) {
                                        if (myAppointment == null) {
                                          getAppointment();
                                          setState(() {
                                            _haveAppointment = value;
                                          });
                                        }
                                      },
                                    ),
                                    Text(
                                      TranslationBase.of(context).yes,
                                      style: TextStyle(
                                        fontSize: 12.0,
                                        letterSpacing: -0.48,
                                        fontWeight: FontWeight.w600,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ),
                        ),
                        Expanded(
                          child: InkWell(
                            onTap: () {
                              setState(() {
                                _haveAppointment = HaveAppointment.NO;
                                myAppointment = null;
                              });
                            },
                            child: Container(
                              child: ListTile(
                                contentPadding: EdgeInsets.only(left: 0.0, right: 0.0),
                                title: Row(
                                  children: [
                                    Radio(
                                      value: HaveAppointment.NO,
                                      groupValue: _haveAppointment,
                                      onChanged: (value) {
                                        setState(() {
                                          _haveAppointment = value;
                                          myAppointment = null;
                                        });
                                      },
                                    ),
                                    Text(
                                      TranslationBase.of(context).no,
                                      style: TextStyle(
                                        fontSize: 12.0,
                                        letterSpacing: -0.48,
                                        fontWeight: FontWeight.w600,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    if (myAppointment != null)
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          SizedBox(
                            height: 12,
                          ),
                          AppointmentCard(
                            appointment: myAppointment,
                          )
                        ],
                      ),
                    SizedBox(
                      height: 12,
                    ),
                    Text(TranslationBase.of(context).dropoffLocation, style: TextStyle(fontSize: 16.0, letterSpacing: -0.64, fontWeight: FontWeight.w600)),
                    SizedBox(
                      height: 8,
                    ),
                    Container(
                      padding: EdgeInsets.only(left: 16, right: 16, bottom: 15, top: 15),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(12),
                        color: Colors.white,
                        border: Border.all(
                          color: Color(0xffefefef),
                          width: 1,
                        ),
                      ),
                      child: InkWell(
                        onTap: () {
                          confirmSelectHospitalDialog(widget.amRequestViewModel.hospitals);
                        },
                        child: Row(
                          children: [
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    TranslationBase.of(context).selectHospital,
                                    style: TextStyle(
                                      fontSize: 11,
                                      fontWeight: FontWeight.w600,
                                      color: Color(0xff2B353E),
                                      letterSpacing: -0.44,
                                    ),
                                  ),
                                  Text(
                                    getHospitalName(""),
                                    style: TextStyle(
                                      fontSize: 14,
                                      height: 21 / 14,
                                      fontWeight: FontWeight.w400,
                                      color: Color(0xff2B353E),
                                      letterSpacing: -0.44,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            Icon(Icons.arrow_drop_down),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              if (widget.patientER_RC.transportationDetails.direction == 0)
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(TranslationBase.of(context).pickupLocation, style: TextStyle(fontSize: 16.0, letterSpacing: -0.64, fontWeight: FontWeight.w600)),
                    SizedBox(
                      height: 15,
                    ),
                    Container(
                      padding: EdgeInsets.only(left: 16, right: 16, bottom: 15, top: 15),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(12),
                        color: Colors.white,
                        border: Border.all(
                          color: Color(0xffefefef),
                          width: 1,
                        ),
                      ),
                      child: InkWell(
                        onTap: () {
                          confirmSelectHospitalDialog(widget.amRequestViewModel.hospitals);
                        },
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    TranslationBase.of(context).selectHospital,
                                    style: TextStyle(
                                      fontSize: 11,
                                      fontWeight: FontWeight.w600,
                                      color: Color(0xff2B353E),
                                      letterSpacing: -0.44,
                                    ),
                                  ),
                                  Text(
                                    getHospitalName(""),
                                    style: TextStyle(
                                      fontSize: 14,
                                      height: 21 / 14,
                                      fontWeight: FontWeight.w400,
                                      color: Color(0xff2B353E),
                                      letterSpacing: -0.44,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            Icon(
                              Icons.arrow_drop_down,
                              size: 24,
                              color: Colors.black,
                            )
                          ],
                        ),
                      ),
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    Text(TranslationBase.of(context).dropoffLocation, style: TextStyle(fontSize: 16.0, letterSpacing: -0.64, fontWeight: FontWeight.w600)),
                    SizedBox(
                      height: 8,
                    ),
                    Container(
                      padding: EdgeInsets.only(left: 16, right: 16, bottom: 15, top: 15),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(12),
                        color: Colors.white,
                        border: Border.all(
                          color: Color(0xffefefef),
                          width: 1,
                        ),
                      ),
                      child: InkWell(
                        onTap: () {
                          Navigator.push(
                            context,
                            FadePage(
                              page: PickupLocationFromMap(
                                latitude: _latitude,
                                longitude: _longitude,
                                onPick: (value) {
                                  setState(() {
                                    _result = value;
                                  });
                                },
                              ),
                            ),
                          );
                        },
                        child: Row(
                          children: [
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    TranslationBase.of(context).selectMap,
                                    style: TextStyle(
                                      fontSize: 11,
                                      fontWeight: FontWeight.w600,
                                      color: Color(0xff2B353E),
                                      letterSpacing: -0.44,
                                    ),
                                  ),
                                  Text(
                                    getSelectFromMapName(context),
                                    style: TextStyle(
                                      fontSize: 14,
                                      height: 21 / 14,
                                      fontWeight: FontWeight.w400,
                                      color: Color(0xff2B353E),
                                      letterSpacing: -0.44,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            Icon(Icons.arrow_drop_down),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              SizedBox(
                height: 45,
              ),
              if (myAppointment != null)
                SizedBox(
                  height: 100,
                ),
            ],
          ),
        ),
      ),
      bottomSheet: Container(
        color: Theme.of(context).scaffoldBackgroundColor,
        padding: EdgeInsets.all(12.0),
        child: DefaultButton(
          // color: Colors.grey[800],
          // textColor: Colors.white,
          TranslationBase.of(context).next,
          () {
            if (_result == null || _selectedHospital == null)
              AppToast.showErrorToast(message: TranslationBase.of(context).selectAll);
            else
              setState(() {
                widget.patientER_RC.transportationDetails.pickupSpot = _isInsideHome ? 1 : 0;
                if (widget.patientER_RC.transportationDetails.direction == 0) {
                  widget.patientER_RC.transportationDetails.dropoffLatitude = _result.geometry.location.lat.toString();
                  widget.patientER_RC.transportationDetails.dropoffLongitude = _result.geometry.location.lng.toString();
                  widget.patientER_RC.transportationDetails.pickupLatitude = _selectedHospital.latitude;
                  widget.patientER_RC.transportationDetails.pickupLongitude = _selectedHospital.longitude;
                } else {
                  widget.patientER_RC.transportationDetails.pickupLatitude = _selectedHospital.latitude;
                  widget.patientER_RC.transportationDetails.pickupLongitude = _selectedHospital.longitude;
                  widget.patientER_RC.transportationDetails.dropoffLatitude = _result.geometry.location.lat.toString();
                  widget.patientER_RC.transportationDetails.dropoffLongitude = _result.geometry.location.lng.toString();
                }

                // widget.patientER.latitude =
                //     widget.patientER.pickupLocationLattitude;
                // widget.patientER.longitude =
                //     widget.patientER.pickupLocationLongitude;

                widget.patientER_RC.transportationDetails.dropoffLocationName = widget.patientER.direction == 0 ? _result.formattedAddress : _selectedHospital.name;
                // widget.patientER_RC.crea =
                //     widget.amRequestViewModel.user.patientID;
                widget.patientER_RC.patientOutSA = widget.amRequestViewModel.user.outSA == 0 ? true : false;
                widget.patientER_RC.patientOutSa = widget.amRequestViewModel.user.outSA;

                widget.patientER_RC.patientIdentificationID = widget.amRequestViewModel.user.patientIdentificationNo;
                widget.patientER_RC.transportationDetails.pickupDateTime = DateUtil.convertDateToStringLocation(DateTime.now());
                widget.patientER_RC.transportationDetails.pickupLocationName = widget.patientER.direction == 0 ? _selectedHospital.name : _result.formattedAddress;
                widget.patientER_RC.projectID = widget.amRequestViewModel.user.projectID;
                widget.patientER_RC.patientID = widget.amRequestViewModel.user.patientID;
                widget.patientER_RC.transportationDetails.requesterIsOutSA = false;
                // widget.patientER.lineItemNo = 0;
                widget.patientER_RC.transportationDetails.requesterMobileNo = widget.amRequestViewModel.user.mobileNumber;

                if (_haveAppointment == HaveAppointment.YES) {
                  widget.patientER_RC.transportationDetails.appointmentNo = myAppointment.appointmentNo.toString();
                  widget.patientER_RC.transportationDetails.appointmentClinicName = myAppointment.clinicName;
                  widget.patientER_RC.transportationDetails.appointmentDoctorName = myAppointment.doctorNameObj;
                  widget.patientER_RC.transportationDetails.appointmentBranch = myAppointment.projectName;
                  widget.patientER_RC.transportationDetails.appointmentTime = myAppointment.appointmentDate;
                  widget.patientER_RC.transportationDetails.haveAppointment = 1;
                } else {
                  widget.patientER_RC.transportationDetails.appointmentNo = "0";
                  widget.patientER_RC.transportationDetails.appointmentClinicName = "";
                  widget.patientER_RC.transportationDetails.appointmentDoctorName = "";
                  widget.patientER_RC.transportationDetails.appointmentBranch = "";
                  widget.patientER_RC.transportationDetails.appointmentTime = "";
                  widget.patientER_RC.transportationDetails.haveAppointment = 0;
                }

                widget.patientER_RC.transportationDetails.pickupSpot = _isInsideHome ? 1 : 0;
                widget.changeCurrentTab(2);
              });
          },
          // label: TranslationBase.of(context).next,
        ),
      ),
    );
  }

  int _selectedHospitalIndex = -1;

  void confirmSelectHospitalDialog(List<HospitalsModel> hospitals) {
    List<RadioSelectionDialogModel> list = [
      for (int i = 0; i < hospitals.length; i++) RadioSelectionDialogModel(hospitals[i].name + ' ${hospitals[i].distanceInKilometers} ' + TranslationBase.of(context).km, i),
    ];
    showDialog(
      context: context,
      builder: (cxt) => RadioSelectionDialog(
        listData: list,
        selectedIndex: _selectedHospitalIndex,
        isScrollable: true,
        onValueSelected: (index) {
          _selectedHospitalIndex = index;
          _selectedHospital = hospitals[index];
          setState(() {});
        },
      ),
    );
  }

  String getHospitalName(String title) {
    return _selectedHospital == null ? title : _selectedHospital.name;
  }

  String getSelectFromMapName(context) {
    return _result != null ? _result.formattedAddress : "";
  }

  getAppointment() {
    GifLoaderDialogUtils.showMyDialog(context);
    widget.amRequestViewModel.getAppointmentHistory().then((value) {
      if (widget.amRequestViewModel.state == ViewState.Error || widget.amRequestViewModel.state == ViewState.ErrorLocal) {
        AppToast.showErrorToast(message: widget.amRequestViewModel.error);
      } else if (widget.amRequestViewModel.appoitmentAllHistoryResultList.length > 0) {
        GifLoaderDialogUtils.hideDialog(context);
        Navigator.push(
          context,
          FadePage(
            page: AvailableAppointmentsPage(
              appointmentsAllHistoryList: widget.amRequestViewModel.appoitmentAllHistoryResultList,
            ),
          ),
        ).then((value) {
          if (value != null)
            setState(() {
              myAppointment = value;
            });
          else {
            ProgressDialogUtil.hideProgressDialog(context);
            setState(() {
              _haveAppointment = HaveAppointment.NO;
            });
          }
        });
      } else {
        GifLoaderDialogUtils.hideDialog(context);
        setState(() {
          _haveAppointment = HaveAppointment.NO;
        });
        AppToast.showErrorToast(message: TranslationBase.of(context).noAppointment);
      }
    }).catchError((e) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: e);
    });
  }
}
