import 'dart:io';

import 'package:diplomaticquarterapp/core/enum/viewstate.dart';
import 'package:diplomaticquarterapp/core/model/AlHabibMedicalService/EReferral/create_e_referral_request_model.dart';
import 'package:diplomaticquarterapp/core/model/AlHabibMedicalService/EReferral/get_all_cities_response_model.dart';
import 'package:diplomaticquarterapp/core/model/hospitals/hospitals_model.dart';
import 'package:diplomaticquarterapp/core/viewModels/all_habib_medical_services/e_referral_view_model.dart';
import 'package:diplomaticquarterapp/models/Authentication/authenticated_user.dart';
import 'package:diplomaticquarterapp/models/FamilyFiles/GetAllSharedRecordByStatusResponse.dart';
import 'package:diplomaticquarterapp/pages/AlHabibMedicalService/ComprehensiveMedicalCheckup/Dialog/confirm_dialog.dart';
import 'package:diplomaticquarterapp/pages/base/base_view.dart';
import 'package:diplomaticquarterapp/services/clinic_services/get_clinic_service.dart';
import 'package:diplomaticquarterapp/theme/colors.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart';
import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.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/bottom_options/BottomSheet.dart';
import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart';
import 'package:diplomaticquarterapp/widgets/data_display/text.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import '../dialogs/select_city_dialog.dart';

class NewEReferralStepThreePage extends StatefulWidget {
  final CreateEReferralRequestModel createEReferralRequestModel;
  final Function changePageViewIndex;

  const NewEReferralStepThreePage({Key key, this.createEReferralRequestModel, this.changePageViewIndex}) : super(key: key);

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

class _NewEReferralStepThreePageState extends State<NewEReferralStepThreePage> {
  TextEditingController _nameTextController = TextEditingController();
  TextEditingController _mobileTextController = TextEditingController();
  GetAllCitiesResponseModel _selectedCity;

  GetAllSharedRecordsByStatusList selectedPatientFamily;
  List<EReferralAttachment> medicalReportImages = [];
  List<EReferralAttachment> insuredPatientImages = [];

  List<HospitalsModel> projectsList = [];

  bool isPatientInsured = false;
  AppSharedPreferences sharedPref = AppSharedPreferences();
  AuthenticatedUser authUser;

  final GlobalKey projectDropdownKey = GlobalKey();
  String projectDropdownValue;

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

  @override
  Widget build(BuildContext context) {
    return BaseView<EReferralViewModel>(
        onModelReady: (model) {
          getAllProjects();
        },
        builder: (_, model, widget) => AppScaffold(
            isShowAppBar: false,
            backgroundColor: CustomColors.appBackgroudGrey2Color,
            body: SingleChildScrollView(
              physics: ScrollPhysics(),
              child: Container(
                margin: EdgeInsets.all(12),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SizedBox(
                      height: 20,
                    ),
                    Text(
                      TranslationBase.of(context).otherInfo,
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                        letterSpacing: -0.64,
                      ),
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    Container(
                      padding: EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(12),
                        color: Colors.white,
                      ),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  TranslationBase.of(context).medicalReport,
                                  style: TextStyle(
                                    fontSize: 12,
                                    letterSpacing: -0.48,
                                    fontWeight: FontWeight.w600,
                                  ),
                                ),
                                ...List.generate(
                                  medicalReportImages.length,
                                  (index) => Container(
                                    padding: EdgeInsets.only(top: 6, bottom: 6),
                                    child: Row(
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: <Widget>[
                                        Row(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: <Widget>[
                                            Texts(
                                              medicalReportImages[index].fileName,
                                            ),
                                          ],
                                        ),
                                        InkWell(
                                            onTap: () {
                                              setState(() {
                                                medicalReportImages.remove(medicalReportImages[index]);
                                              });
                                            },
                                            child: Icon(
                                              Icons.close,
                                              color: Colors.red[300],
                                            ))
                                      ],
                                    ),
                                  ),
                                ),
                                InkWell(
                                  onTap: () {
                                    ImageOptions.showImageOptions(
                                      context,
                                      (String image, File file) {
                                        setState(() {
                                          EReferralAttachment eReferralAttachment = new EReferralAttachment(fileName: 'image ${medicalReportImages.length + 1}.png', base64String: image);
                                          medicalReportImages.add(eReferralAttachment);
                                        });
                                      },
                                    );
                                  },
                                  child: Padding(
                                    padding: EdgeInsets.only(top: 12, bottom: 12),
                                    child: Text(
                                      TranslationBase.of(context).selectAttachment,
                                      style: TextStyle(
                                        fontSize: 14,
                                        letterSpacing: -0.56,
                                        decoration: TextDecoration.underline,
                                        color: CustomColors.accentColor,
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Icon(Icons.attach_file),
                        ],
                      ),
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    Container(
                      padding: EdgeInsets.only(top: 10),
                      decoration: BoxDecoration(borderRadius: BorderRadius.circular(12), color: Colors.white),
                      child: Column(
                        children: [
                          Container(
                              width: double.infinity,
                              decoration: containerRadius(Colors.white, 12),
                              margin: EdgeInsets.only(left: 20, right: 20),
                              padding: EdgeInsets.only(left: 10, right: 10, top: 12, bottom: 12),
                              child: Row(
                                children: [
                                  Flexible(
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Text(
                                          TranslationBase.of(context).preferredBranch,
                                          style: TextStyle(
                                            fontSize: 11,
                                            letterSpacing: -0.44,
                                            fontWeight: FontWeight.w600,
                                          ),
                                        ),
                                        Container(
                                          height: 18,
                                          child: DropdownButtonHideUnderline(
                                            child: DropdownButton<String>(
                                              key: projectDropdownKey,
                                              hint: Text(TranslationBase.of(context).selectPreferredBranch),
                                              value: projectDropdownValue,
                                              iconSize: 0,
                                              isExpanded: true,
                                              style: TextStyle(fontSize: 14, letterSpacing: -0.56, color: Colors.black),
                                              items: projectsList.map((item) {
                                                return new DropdownMenuItem<String>(
                                                  value: item.mainProjectID.toString() + "," + item.name.toString(),
                                                  child: new Text(item.name),
                                                );
                                              }).toList(),
                                              onChanged: (newValue) {
                                                setState(() {
                                                  projectDropdownValue = newValue;
                                                  print(projectDropdownValue);
                                                });
                                              },
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                  Icon(Icons.keyboard_arrow_down),
                                ],
                              )),
                        ],
                      ),
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    Container(
                      // decoration: BoxDecoration(borderRadius: BorderRadius.circular(12), color: Colors.white),
                      child: Column(
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Row(
                                children: [
                                  Checkbox(
                                      value: isPatientInsured,
                                      activeColor: CustomColors.accentColor,
                                      onChanged: (bool newValue) {
                                        setState(() {
                                          isPatientInsured = newValue;
                                        });
                                      }),
                                  Padding(
                                    padding: const EdgeInsets.all(5.0),
                                    child: Text(
                                      TranslationBase.of(context).insuredPatientReferral,
                                      style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600),
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                    if (isPatientInsured)
                      SizedBox(
                        height: 12,
                      ),
                    Opacity(
                      opacity: isPatientInsured ? 1 : 0,
                      child: Container(
                        padding: EdgeInsets.all(10),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(12),
                          color: Colors.white,
                        ),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    TranslationBase.of(context).medicalReport,
                                    style: TextStyle(
                                      fontSize: 12,
                                      letterSpacing: -0.48,
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                                  ...List.generate(
                                    insuredPatientImages.length,
                                    (index) => Container(
                                      padding: EdgeInsets.only(top: 6, bottom: 6),
                                      child: Row(
                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        children: <Widget>[
                                          Row(
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            children: <Widget>[
                                              Texts(
                                                'image ${index + 1}.png',
                                              ),
                                            ],
                                          ),
                                          InkWell(
                                            onTap: () {
                                              setState(() {
                                                insuredPatientImages.remove(insuredPatientImages[index]);
                                              });
                                            },
                                            child: Icon(
                                              Icons.close,
                                              color: Colors.red[300],
                                            ),
                                          )
                                        ],
                                      ),
                                    ),
                                  ),
                                  InkWell(
                                    onTap: () {
                                      ImageOptions.showImageOptions(context, (String image, File file) {
                                        setState(() {
                                          EReferralAttachment eReferralAttachment = new EReferralAttachment(fileName: 'image ${medicalReportImages.length + 1}.png', base64String: image);
                                          insuredPatientImages = [eReferralAttachment];
                                        });
                                      });
                                    },
                                    child: Padding(
                                      padding: const EdgeInsets.only(top: 12, bottom: 12),
                                      child: Text(
                                        TranslationBase.of(context).selectAttachment,
                                        style: TextStyle(
                                          fontSize: 14,
                                          letterSpacing: -0.56,
                                          decoration: TextDecoration.underline,
                                          color: CustomColors.accentColor,
                                        ),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            Icon(Icons.attach_file),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            bottomSheet: Container(
              color: Theme.of(context).scaffoldBackgroundColor,
              width: double.infinity,
              padding: EdgeInsets.all(9),
              child: DefaultButton(
                TranslationBase.of(context).submit,
                medicalReportImages.length == 0
                    ? null
                    : () async {
                        Future.delayed(new Duration(milliseconds: 300)).then((value) async {
                          GifLoaderDialogUtils.showMyDialog(context);
                          this.widget.createEReferralRequestModel.medicalReportAttachment = medicalReportImages;
                          this.widget.createEReferralRequestModel.insuranceCardAttachment = insuredPatientImages.length != 0 ? insuredPatientImages[0] : null;
                          this.widget.createEReferralRequestModel.isInsuredPatient = isPatientInsured;
                          // ToDo make the preferred Branch info dynamic
                          this.widget.createEReferralRequestModel.preferredBranchCode = projectDropdownValue != null && projectDropdownValue.isNotEmpty ? num.tryParse(projectDropdownValue.split(",")[0]) : 0;
                          this.widget.createEReferralRequestModel.preferredBranchName = projectDropdownValue != null && projectDropdownValue.isNotEmpty ? projectDropdownValue.split(",")[1] : "";
                          // this.widget.createEReferralRequestModel.otherRelationship = "";
                          await model.createEReferral(this.widget.createEReferralRequestModel);
                          if (model.state == ViewState.ErrorLocal) {
                            GifLoaderDialogUtils.hideDialog(context);
                            Utils.showErrorToast(model.error);
                          } else {
                            GifLoaderDialogUtils.hideDialog(context);
                            // AppToast.showSuccessToast(message: TranslationBase.of(context).ereferralSaveSuccess);
                            showCMCConfirmDialog(
                              context,
                              model.referralNumber,
                              onClick: () {
                                Navigator.pop(context);
                              },
                            );
                          }
                        });
                      },
                disabledColor: Colors.grey,
                color: Color(0xff359846),
              ),

              // SecondaryButton(
              //   textColor: Colors.white,
              //   label: "Submit",
              //   onTap: () async {
              //     this
              //         .widget
              //         .createEReferralRequestModel
              //         .medicalReportAttachment = medicalReportImages;
              //     this
              //             .widget
              //             .createEReferralRequestModel
              //             .insuranceCardAttachment =
              //         insuredPatientImages.length != 0
              //             ? insuredPatientImages[0]
              //             : null;
              //     this.widget.createEReferralRequestModel.isInsuredPatient =
              //         isPatientInsured;
              //     // ToDo make the preferred Branch info dynamic
              //     this.widget.createEReferralRequestModel.preferredBranchCode =
              //         15;
              //     this.widget.createEReferralRequestModel.preferredBranchName =
              //         "Arryan Hospital";
              //     this.widget.createEReferralRequestModel.otherRelationship =
              //         "";
              //
              //     await model
              //         .createEReferral(this.widget.createEReferralRequestModel);
              //     if(model.state == ViewState.ErrorLocal) {
              //       Utils.showErrorToast(model.error);
              //     } else{
              //       AppToast.showSuccessToast(message: "Referral sent successfully");
              //     }
              //   },
              //   loading: model.state == ViewState.BusyLocal,
              //   disabled: medicalReportImages.length == 0,
              // ),
            )));
  }

  void getAllProjects() {
    ClinicListService service = new ClinicListService();
    List<HospitalsModel> projectsListLocal = [];
    service.getProjectsList(context).then((res) {
      if (res['MessageStatus'] == 1) {
        setState(() {
          res['ListProject'].forEach((v) {
            projectsListLocal.add(new HospitalsModel.fromJson(v));
          });
          projectsList = projectsListLocal;
        });
        // isProjectLoaded = true;
      } else {
        // isProjectLoaded = false;
      }
    }).catchError((err) {
      print(err);
    });
  }

  void confirmSelectCityDialog(List<GetAllCitiesResponseModel> cities) {
    showDialog(
      context: context,
      builder: (cxt) => SelectCityDialog(
        cities: cities,
        selectedCity: _selectedCity,
        onValueSelected: (value) {
          setState(() {
            _selectedCity = value;
          });
        },
      ),
    );
  }

  String getRelationName() {
    if (_selectedCity != null)
      return _selectedCity.description;
    else
      return "Select Relationship" /*TranslationBase.of(context).selectHospital*/;
  }
}
