import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/config/size_config.dart';
import 'package:doctor_app_flutter/core/enum/view_state.dart';
import 'package:doctor_app_flutter/core/model/PatientRegistration/PatientRegistrationModel.dart';
import 'package:doctor_app_flutter/core/model/patient/patiant_info_model.dart';
import 'package:doctor_app_flutter/core/viewModel/PatientRegistrationViewModel.dart';
import 'package:doctor_app_flutter/core/viewModel/profile/operation_report_view_model.dart';
import 'package:doctor_app_flutter/core/viewModel/project_view_model.dart';
import 'package:doctor_app_flutter/icons_app/doctor_app_icons.dart';
import 'package:doctor_app_flutter/utils/date-utils.dart';
import 'package:doctor_app_flutter/utils/dr_app_toast_msg.dart';
import 'package:doctor_app_flutter/utils/translations_delegate_base_utils.dart';
import 'package:doctor_app_flutter/utils/utils.dart';
import 'package:doctor_app_flutter/widgets/shared/app_scaffold_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/app_texts_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/buttons/app_buttons_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/loader/gif_loader_dialog_utils.dart';
import 'package:doctor_app_flutter/widgets/shared/text_fields/app-textfield-custom.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:intl/intl.dart';
import 'package:jhijri_picker/_src/_jWidgets.dart';
import 'package:provider/provider.dart';

import 'CustomEditableText.dart';

class RegisterConfirmationPatientPage extends StatefulWidget {
  final OperationReportViewModel? operationReportViewModel;
  final PatiantInformtion? patient;
  final PatientRegistrationViewModel? model;

  const RegisterConfirmationPatientPage({Key? key, this.operationReportViewModel, this.patient, this.model}) : super(key: key);

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

class _RegisterConfirmationPatientPageState extends State<RegisterConfirmationPatientPage> {
  bool isSubmitted = false;
  late ProjectViewModel projectViewModel;
  TextEditingController firstNameN = TextEditingController(), middleNameN = TextEditingController(), lastNameN = TextEditingController();
  TextEditingController firstNameAr = TextEditingController();
  TextEditingController middleNameAr = TextEditingController();
  TextEditingController lastNameAr = TextEditingController();
  TextEditingController emailAddressController = TextEditingController();
  TextEditingController langController = TextEditingController(text: "English");
  int selectedLang = 1;

  @override
  void initState() {
    firstNameN = TextEditingController(text: widget.model!.getPatientInfoResponseModel.firstNameEn);
    middleNameN = TextEditingController(text: "");
    lastNameN = TextEditingController(text: widget.model!.getPatientInfoResponseModel.lastNameEn);

    firstNameAr = TextEditingController(text: widget.model!.getPatientInfoResponseModel.firstNameAr);
    middleNameAr = TextEditingController(text: "");
    lastNameAr = TextEditingController(text: widget.model!.getPatientInfoResponseModel.lastNameAr);
    emailAddressController = TextEditingController(text: "");
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);

    ///TODO Elham* add translation
    return AppScaffold(
      isShowAppBar: false,
      backgroundColor: Color(0xFFF8F8F8),
      body: SingleChildScrollView(
        child: Container(
          height: MediaQuery.of(context).size.height * 1.0,
          child: Padding(
            padding: EdgeInsets.all(0.0),
            child: SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SizedBox(
                    height: 10.0,
                  ),
                  SingleChildScrollView(
                    child: Center(
                      child: FractionallySizedBox(
                        widthFactor: 0.9,
                        child: Column(
                          children: [
                            CustomEditableText(controller: firstNameN, isSubmitted: isSubmitted, hint: TranslationBase.of(context).firstName),
                            SizedBox(
                              height: 4,
                            ),
                            CustomEditableText(controller: middleNameN, isEditable: middleNameN.text.isEmpty, isSubmitted: isSubmitted, hint: TranslationBase.of(context).middleName),
                            SizedBox(
                              height: 4,
                            ),
                            CustomEditableText(controller: lastNameN, isSubmitted: isSubmitted, hint: TranslationBase.of(context).lastName),
                            SizedBox(
                              height: 20,
                            ),
                            CustomEditableText(controller: firstNameAr, isSubmitted: isSubmitted, hint: TranslationBase.of(context).firstNameInAr),
                            SizedBox(
                              height: 4,
                            ),
                            CustomEditableText(controller: middleNameAr, isEditable: middleNameN.text.isEmpty, isSubmitted: isSubmitted, hint: TranslationBase.of(context).middleNameInAr),
                            SizedBox(
                              height: 4,
                            ),
                            CustomEditableText(controller: lastNameAr, isSubmitted: isSubmitted, hint: TranslationBase.of(context).lastNameInAr),
                            SizedBox(
                              height: 20,
                            ),
                            FractionallySizedBox(
                              widthFactor: .9,
                              child: Center(
                                child: Column(
                                  children: [
                                    Row(
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: [
                                        Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            AppText(TranslationBase.of(context).healthID, fontSize: 12, color: Colors.black),
                                            AppText(
                                              "${widget.model!.getPatientInfoResponseModel.healthId}",
                                              fontSize: 12,
                                              color: Colors.grey[600]!,
                                            ),
                                          ],
                                        ),
                                        Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            AppText(TranslationBase.of(context).identityNumber, fontSize: 12, color: Colors.black),
                                            AppText(
                                              "${widget.model!.getPatientInfoResponseModel.idNumber}",
                                              fontSize: 12,
                                              color: Colors.grey[600]!,
                                            ),
                                          ],
                                        ),
                                        SizedBox(
                                          width: 20,
                                        )
                                      ],
                                    ),
                                    SizedBox(
                                      height: 20,
                                    ),
                                    Row(
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: [
                                        Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            AppText(TranslationBase.of(context).nationality, fontSize: 12, color: Colors.black),
                                            AppText(
                                              "${widget.model!.getPatientInfoResponseModel.nationality}",
                                              fontSize: 12,
                                              color: Colors.grey[600]!,
                                            ),
                                          ],
                                        ),
                                        Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            AppText(TranslationBase.of(context).occupation, fontSize: 12, color: Colors.black),
                                            AppText(
                                              "${widget.model!.getPatientInfoResponseModel.occupation}",
                                              fontSize: 12,
                                              color: Colors.grey[600]!,
                                            ),
                                          ],
                                        ),
                                        SizedBox(
                                          width: 20,
                                        )
                                      ],
                                    ),
                                    SizedBox(
                                      height: 20,
                                    ),
                                    Row(
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: [
                                        Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            AppText(TranslationBase.of(context).mobileNo, fontSize: 12, color: Colors.black),
                                            AppText(
                                              "${widget.model!.checkPatientForRegistrationModel!.patientMobileNumber}",
                                              fontSize: 12,
                                              color: Colors.grey[600]!,
                                            ),
                                          ],
                                        ),
                                        SizedBox(
                                          width: 20,
                                        )
                                      ],
                                    ),
                                    SizedBox(
                                      height: 20,
                                    ),
                                  ],
                                ),
                              ),
                            ),
                            AppTextFieldCustom(
                              height: Utils.getTextFieldHeight(),
                              enabled: false,
                              onClick: () {
                                openMaritalStatusList(context);
                              },
                              hintText: TranslationBase.of(context).maritalStatus,
                              maxLines: 1,
                              minLines: 1,
                              isTextFieldHasSuffix: true,

                              // controller: doseController,
                              // validationError: isFormSubmitted &&
                              //     _selectedMedicationDose == null
                              //     ? TranslationBase.of(context)
                              //     .emptyMessage
                              //     : null,
                              onChanged: (value) {},
                              onFieldSubmitted: () {},
                            ),
                            SizedBox(
                              height: 20,
                            ),
                            AppTextFieldCustom(
                              height: Utils.getTextFieldHeight(),
                              enabled: false,
                              onClick: () {
                                openLangList(context);
                              },
                              controller: langController,
                              hintText: TranslationBase.of(context).lanEnglish,
                              maxLines: 1,
                              minLines: 1,
                              isTextFieldHasSuffix: true,
                              // controller: doseController,
                              // validationError: isFormSubmitted &&
                              //     _selectedMedicationDose == null
                              //     ? TranslationBase.of(context)
                              //     .emptyMessage
                              //     : null,
                              onChanged: (value) {},
                              onFieldSubmitted: () {},
                            ),
                            SizedBox(
                              height: 20,
                            ),
                            AppTextFieldCustom(
                              hintText: "Email Address",
                              //TranslationBase.of(context).addoperationReports,
                              controller: emailAddressController,
                              maxLines: 1,
                              minLines: 1,
                              hasBorder: true,
                              validationError: emailAddressController.text.isEmpty && isSubmitted ? TranslationBase.of(context).emptyMessage : "",

                              onClick: () {},
                              onChanged: (value) {},
                              onFieldSubmitted: () {},
                            ),
                            SizedBox(
                              height: 400,
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
      bottomSheet: Container(
        height: 60,
        margin: EdgeInsets.symmetric(vertical: 16, horizontal: 16),
        child: Row(
          children: [
            Expanded(
              child: Container(
                child: AppButton(
                  title: TranslationBase.of(context).cancel,
                  hasBorder: true,
                  vPadding: 12,
                  hPadding: 8,
                  borderColor: Color(0xFFeaeaea),
                  color: Color(0xFFeaeaea),
                  fontColor: Colors.black,
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
              ),
            ),
            SizedBox(
              width: 8,
            ),
            Expanded(
              child: Container(
                child: AppButton(
                  title: TranslationBase.of(context).next,
                  hasBorder: true,
                  vPadding: 12,
                  hPadding: 8,
                  borderColor: Color(0xFFB8382B),
                  color: HexColor("#D02127"),
                  fontColor: Colors.white,
                  onPressed: () async {
                    setState(() {
                      isSubmitted = true;
                    });
                    if (isFormValid()) {
                      print(widget.model!.getPatientInfoResponseModel.dateOfBirth);

                      var dateFormat = DateFormat('MM/dd/yyyy').parse(widget.model!.getPatientInfoResponseModel.dateOfBirth!);
                      String wellFormat = "${dateFormat.day}\/${dateFormat.month}\/${dateFormat.year}";
                      print(
                        dateFormat.toUtc().toString(),
                      );
                      JDateModel hijriDate = JDateModel(
                        dateTime: DateTime(dateFormat.year, dateFormat.month, dateFormat.day),
                      );
                      // return ;

                      GifLoaderDialogUtils.showMyDialog(context);
                      PatientRegistrationModel patientRegistrationModel = PatientRegistrationModel(
                          patientobject: Patientobject(
                              tempValue: true,
                              patientIdentificationNo: widget.model!.checkPatientForRegistrationModel!.patientIdentificationID.toString(),
                              patientIdentificationType: 1,
                              firstName: firstNameAr.text,
                              firstNameN: firstNameN.text,
                              lastName: lastNameAr.text,
                              lastNameN: lastNameN.text,
                              middleName: middleNameAr.text,
                              middleNameN: middleNameN.text,
                              strDateofBirth: dateFormat.toUtc().toString(),
                              dateofBirth: AppDateUtils.convertToServerFormat(widget.model!.getPatientInfoResponseModel.dateOfBirth!, 'MM/dd/yyyy'),
                              dateofBirthN: '$hijriDate',
                              gender: (widget.model!.getPatientInfoResponseModel.gender == "M") ? 1 : 2,
                              sourceType: "1",
                              patientOutSA: 0,
                              nationalityID: widget.model!.getPatientInfoResponseModel.nationalityCode,
                              //todo Elham* change static value to dynamic
                              preferredLanguage: selectedLang.toString(),
                              marital: "0",
                              eHealthIDField: widget.model!.getPatientInfoResponseModel.healthId,
                              emailAddress: emailAddressController.text,
                              mobileNumber: widget.model!.checkPatientForRegistrationModel!.patientMobileNumber),
                          isHijri: 0,
                          logInTokenID: "zjgvKtLC/EK+saznJ/OkiA==",
                          isDentalAllowedBackend: false,
                          patientOutSA: 0,
                          sessionID: null,
                          patientMobileNumber: widget.model!.checkPatientForRegistrationModel!.patientMobileNumber.toString(),
                          healthId: widget.model!.getPatientInfoResponseModel.healthId,
                          generalid: GENERAL_ID,
                          patientIdentificationID: widget.model!.checkPatientForRegistrationModel!.patientIdentificationID.toString(),
                          dOB: wellFormat,
                          zipCode: widget.model!.checkPatientForRegistrationModel!.zipCode);
                      await widget.model!.registrationPatient(patientRegistrationModel);
                      if (widget.model!.state == ViewState.ErrorLocal) {
                        Utils.showErrorToast(widget.model!.error);
                      } else {
                        DrAppToastMsg.showSuccesToast("Patient added Successfully");
                        Navigator.of(context).pop();
                      }

                      GifLoaderDialogUtils.hideDialog(context);
                    }
                  },
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  openMaritalStatusList(BuildContext context) {
    showModalBottomSheet(
        backgroundColor: Colors.white,
        isDismissible: true,
        isScrollControlled: true,
        context: context,
        builder: (context) {
          return FractionallySizedBox(
            heightFactor: .3,
            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: AppText(
                        "${TranslationBase.of(context).maritalStatus} :",
                        fontFamily: 'Poppins',
                        fontWeight: FontWeight.w700,
                        fontSize: 18,
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: InkWell(
                          onTap: () {
                            Navigator.of(context).pop();
                          },
                          child: Icon(DoctorApp.close_1, size: SizeConfig.getTextMultiplierBasedOnWidth() * 4.5, color: Color(0xFF2B353E))),
                    ),
                  ],
                ),
                SizedBox(
                  height: 10,
                ),
                InkWell(
                  onTap: () {},
                  child: Row(
                    children: [
                      Radio(
                        value: 1,
                        groupValue: 1,
                        onChanged: (value) {
                          setState(() {});
                        },
                        activeColor: Colors.red,
                      ),
                      AppText(
                        "Single",
                        fontFamily: 'Poppins',
                        fontWeight: FontWeight.w600,
                        fontSize: 15,
                      ),
                    ],
                  ),
                ),
                InkWell(
                  onTap: () {},
                  child: Row(
                    children: [
                      Radio(
                        value: 1,
                        groupValue: 1,
                        onChanged: (value) {
                          setState(() {});
                        },
                        activeColor: Colors.red,
                      ),
                      AppText(
                        "Married",
                        fontFamily: 'Poppins',
                        fontWeight: FontWeight.w600,
                        fontSize: 15,
                      ),
                    ],
                  ),
                ),
                InkWell(
                  onTap: () {},
                  child: Row(
                    children: [
                      Radio(
                        value: 1,
                        groupValue: 1,
                        onChanged: (value) {
                          setState(() {});
                        },
                        activeColor: Colors.red,
                      ),
                      AppText(
                        "Divorce",
                        fontFamily: 'Poppins',
                        fontWeight: FontWeight.w600,
                        fontSize: 15,
                      ),
                    ],
                  ),
                ),
              ],
            ),
          );
        });
  }

  openLangList(BuildContext context) {
    showModalBottomSheet(
        backgroundColor: Colors.white,
        isDismissible: true,
        isScrollControlled: true,
        context: context,
        builder: (context) {
          return FractionallySizedBox(
            heightFactor: .3,
            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: AppText(
                        "language:",
                        fontFamily: 'Poppins',
                        fontWeight: FontWeight.w700,
                        fontSize: 18,
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: InkWell(
                          onTap: () {
                            Navigator.of(context).pop();
                          },
                          child: Icon(DoctorApp.close_1, size: SizeConfig.getTextMultiplierBasedOnWidth() * 4.5, color: Color(0xFF2B353E))),
                    ),
                  ],
                ),
                SizedBox(
                  height: 10,
                ),
                InkWell(
                  onTap: () {
                    setSelectedLang(1);
                  },
                  child: Row(
                    children: [
                      Radio(
                        value: 1,
                        groupValue: selectedLang,
                        onChanged: (value) {
                          setSelectedLang(value);
                        },
                        activeColor: Colors.red,
                      ),
                      AppText(
                        TranslationBase.of(context).lanEnglish,
                        fontFamily: 'Poppins',
                        fontWeight: FontWeight.w600,
                        fontSize: 15,
                      ),
                    ],
                  ),
                ),
                InkWell(
                  onTap: () {
                    setSelectedLang(2);
                  },
                  child: Row(
                    children: [
                      Radio(
                        value: 2,
                        groupValue: selectedLang,
                        onChanged: (value) {
                          setSelectedLang(value);
                        },
                        activeColor: Colors.red,
                      ),
                      AppText(
                        TranslationBase.of(context).lanArabic,
                        fontFamily: 'Poppins',
                        fontWeight: FontWeight.w600,
                        fontSize: 15,
                      ),
                    ],
                  ),
                ),
              ],
            ),
          );
        });
  }

  setSelectedLang(lang) {
    setState(() {
      selectedLang = lang;
      langController.text = lang == 1 ? "English" : "العربيه";
    });
    Navigator.of(context).pop();
  }

  bool isFormValid() {
    if (middleNameAr.text != null &&
        middleNameAr.text.isNotEmpty &&
        middleNameN.text != null &&
        middleNameN.text.isNotEmpty &&
        emailAddressController.text != null &&
        emailAddressController.text.isNotEmpty) {
      return true;
    }
    return false;
  }
}
