import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/config/size_config.dart';
import 'package:doctor_app_flutter/core/enum/calender_type.dart';
import 'package:doctor_app_flutter/core/enum/view_state.dart';
import 'package:doctor_app_flutter/core/model/PatientRegistration/CheckPatientForRegistrationModel.dart';
import 'package:doctor_app_flutter/core/model/PatientRegistration/GetPatientInfoRequestModel.dart';
import 'package:doctor_app_flutter/core/viewModel/PatientRegistrationViewModel.dart';
import 'package:doctor_app_flutter/utils/date-utils.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/dialogs/dailog-list-select.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:doctor_app_flutter/widgets/shared/text_fields/country_textfield_custom.dart';
import 'package:flutter/material.dart';
import 'package:jhijri/jHijri.dart';
import 'package:jhijri_picker/jhijri_picker.dart';

class RegisterSearchPatientPage extends StatefulWidget {
  final Function? changePageViewIndex;
  final PatientRegistrationViewModel? model;

  const RegisterSearchPatientPage({Key? key, this.changePageViewIndex, this.model}) : super(key: key);

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

class _RegisterSearchPatientPageState extends State<RegisterSearchPatientPage> {
  String countryError = '';
  dynamic _selectedCountry;

  List<dynamic> countryList = [];

  dynamic country;

  bool isSubmitted = false;

  TextEditingController _phoneController = TextEditingController(text: "508079569");
  TextEditingController _phoneCode = TextEditingController(text: "966");

  String phoneError = '';

  TextEditingController _idController = TextEditingController(text: "1062938285");
  String idError = '';

  DateTime? _birthDateInGregorian;
  String birthdateError = '';

  // var birthDateInHijri = new HijriCalendar.now();
  var birthDateInHijri = JDateModel(jhijri: JHijri.now());
  CalenderType calenderType = CalenderType.Gregorian;

  @override
  void initState() {
    _phoneCode.text = "";
    countryList = [];

    dynamic ksaCountry = {"id": 967, "name": "Saudi Arabia"};
    dynamic uaeCountry = {"id": 971, "name": "United Arab Emirates"};
    dynamic bahrainCountry = {"id": 973, "name": "Bahrain"};
    dynamic kuwaitCountry = {"id": 965, "name": "Kuwait"};
    dynamic afghanistanCountry = {"id": 93, "name": "Afghanistan"};
    dynamic algeriaCountry = {"id": 213, "name": "Algeria"};
    dynamic argentinaCountry = {"id": 54, "name": "Argentina"};
    dynamic bangladeshCountry = {"id": 880, "name": "Bangladesh"};
    dynamic colombiaCountry = {"id": 57, "name": "Colombia"};
    dynamic croatiaCountry = {"id": 385, "name": "Croatia"};
    dynamic denmarkCountry = {"id": 45, "name": "Denmark"};
    dynamic ecuadorCountry = {"id": 593, "name": "Ecuador"};
    dynamic egyptCountry = {"id": 20, "name": "Egypt"};
    dynamic ethiopiaCountry = {"id": 251, "name": "Ethiopia"};
    dynamic greeceCountry = {"id": 30, "name": "Greece"};
    dynamic icelandCountry = {"id": 354, "name": "Iceland"};
    dynamic indonesiaCountry = {"id": 62, "name": "Indonesia"};
    dynamic iraqCountry = {"id": 971, "name": "Iraq"};
    dynamic liberiaCountry = {"id": 231, "name": "Liberia"};
    dynamic senegalCountry = {"id": 221, "name": "Senegal"};

    countryList.add(ksaCountry);
    countryList.add(uaeCountry);
    countryList.add(bahrainCountry);
    countryList.add(kuwaitCountry);
    countryList.add(afghanistanCountry);
    countryList.add(algeriaCountry);
    countryList.add(argentinaCountry);
    countryList.add(bangladeshCountry);
    countryList.add(colombiaCountry);
    countryList.add(croatiaCountry);
    countryList.add(denmarkCountry);
    countryList.add(ecuadorCountry);
    countryList.add(egyptCountry);
    countryList.add(ethiopiaCountry);
    countryList.add(greeceCountry);
    countryList.add(icelandCountry);
    countryList.add(indonesiaCountry);
    countryList.add(iraqCountry);
    countryList.add(liberiaCountry);
    countryList.add(senegalCountry);
    country = countryList[0];
    _phoneCode.text = countryList[0]['id'].toString();
  }

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;

    /// TODO Elham* add transaltion

    return AppScaffold(
      baseViewModel: widget.model!,
      isShowAppBar: false,
      body: Column(
        children: [
          Expanded(
            child: Container(
              width: double.infinity,
              margin: EdgeInsets.all(16.0),
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    AppText(
                      TranslationBase.of(context).askForIdentification,
                      fontFamily: 'Poppins',
                      fontSize: SizeConfig.textMultiplier! * 2.2,
                      fontWeight: FontWeight.w800,
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    CountryTextField(
                      elementList: countryList,
                      element: country,
                      elementError: countryError,
                      keyName: 'name',
                      keyId: 'id',
                      okFunction: (selectedValue) {
                        setState(() {
                          country = selectedValue;
                          _phoneCode.text = selectedValue['id'].toString();
                        });
                      },
                      hintText: "Country",
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    Row(
                      children: [
                        Column(
                          children: [
                            Container(
                              width: MediaQuery.of(context).size.width * 0.28,
                              child: AppTextFieldCustom(
                                height: screenSize.height * 0.075,
                                hintText: TranslationBase.of(context).codeNo,
                                inputType: TextInputType.phone,
                                controller: _phoneCode,
                                validationError: phoneError,
                                enabled: false,
                                onClick: () {},
                                onChanged: (value) {},
                                onFieldSubmitted: () {},
                              ),
                            ),
                            if (_phoneController.text.isEmpty && isSubmitted)
                              SizedBox(
                                height: 35,
                              )
                          ],
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        Expanded(
                          child: Container(
                            // width: MediaQuery.of(context).size.width*0.7,
                            child: AppTextFieldCustom(
                              height: screenSize.height * 0.075,
                              hintText: TranslationBase.of(context).phoneNumber,
                              inputType: TextInputType.phone,
                              controller: _phoneController,
                              validationError: _phoneController.text.isEmpty && isSubmitted ? TranslationBase.of(context).emptyMessage : "",
                              onClick: () {},
                              onChanged: (value) {},
                              onFieldSubmitted: () {},
                            ),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    AppTextFieldCustom(
                      height: screenSize.height * 0.075,
                      hintText: TranslationBase.of(context).iDNumber,
                      inputType: TextInputType.phone,
                      controller: _idController,
                      validationError: _idController.text.isEmpty && isSubmitted ? TranslationBase.of(context).emptyMessage : "",
                      onClick: () {},
                      onChanged: (value) {},
                      onFieldSubmitted: () {},
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    AppText(
                      TranslationBase.of(context).calender,
                      fontSize: SizeConfig.textMultiplier! * 1.8,
                      fontWeight: FontWeight.w800,
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    Row(
                      children: [
                        Expanded(
                          child: RadioListTile<CalenderType>(
                            title: AppText(TranslationBase.of(context).gregorian),
                            value: CalenderType.Gregorian,
                            groupValue: calenderType,
                            onChanged: (CalenderType? value) {
                              setState(() {
                                calenderType = value!;
                              });
                            },
                          ),
                        ),
                        Expanded(
                          child: RadioListTile<CalenderType>(
                            title: AppText(TranslationBase.of(context).hijri),
                            value: CalenderType.Hijri,
                            groupValue: calenderType,
                            onChanged: (CalenderType? value) {
                              setState(() {
                                calenderType = value!;
                              });
                            },
                          ),
                        ),
                      ],
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    AppTextFieldCustom(
                      height: screenSize.height * 0.075,
                      hintText: TranslationBase.of(context).birthdate,
                      dropDownText: getBirthdate(),
                      enabled: false,
                      isTextFieldHasSuffix: true,
                      validationError: _birthDateInGregorian == null && isSubmitted ? TranslationBase.of(context).emptyMessage : "",
                      suffixIcon: IconButton(
                        icon: Icon(
                          Icons.calendar_today,
                          color: Colors.black,
                        ),
                        onPressed: null,
                      ),
                      onClick: () {
                        if (_birthDateInGregorian == null) {
                          _birthDateInGregorian = DateTime.now();
                        }
                        _selectDate(context, _birthDateInGregorian!, (dynamic selectedDate) {
                          setState(() {
                            if (calenderType == CalenderType.Hijri) {
                              birthDateInHijri = selectedDate;
                              // _birthDateInGregorian = HijriCalendar()
                              //     .hijriToGregorian(
                              //         birthDateInHijri.hYear,
                              //         birthDateInHijri.hMonth,
                              //         birthDateInHijri.hDay);
                              //

                              _birthDateInGregorian =
                                  DateTime.parse(JHijri(fDay: birthDateInHijri.jhijri!.day, fMonth: birthDateInHijri.jhijri!.month, fYear: birthDateInHijri.jhijri!.year).toString());

                              print(_birthDateInGregorian);
                              print(birthDateInHijri);
                            } else {
                              _birthDateInGregorian = selectedDate;
                              // birthDateInHijri = HijriCalendar()
                              //     .gregorianToHijri(
                              //     selectedDate.year,
                              //     selectedDate.month,
                              //     selectedDate.day) as HijriCalendar;

                              birthDateInHijri = JDateModel(dateTime: selectedDate);

                              print(_birthDateInGregorian);
                              print(birthDateInHijri.dateTime);
                              print(birthDateInHijri.jhijri);
                            }
                          });
                        });
                      },
                      onChanged: (value) {},
                      onFieldSubmitted: () {},
                    ),
                    SizedBox(
                      height: 70,
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
      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,
                  borderColor: Color(0xFFB8382B),
                  color: AppGlobal.appRedColor,
                  fontColor: Colors.white,
                  onPressed: () async {
                    setState(() {
                      isSubmitted = true;
                    });
                    if (country == null) {
                      countryError = TranslationBase.of(context).fieldRequired;
                    } else {
                      countryError = "";
                    }
                    if (isFormValid()) {
                      GifLoaderDialogUtils.showMyDialog(context);
                      CheckPatientForRegistrationModel checkPatientForRegistrationModel = CheckPatientForRegistrationModel(
                          patientIdentificationID: int.parse(_idController.text),
                          patientMobileNumber: int.parse(_phoneController.text),
                          zipCode: _phoneCode.text,
                          isHijri: 0,
                          patientID: 0,
                          isRegister: false,
                          isDentalAllowedBackend: false,
                          patientOutSA: 0,
                          generalid: GENERAL_ID,
                          dOB: "${AppDateUtils.convertStringToDateFormat(_birthDateInGregorian.toString(), "yyyy/MM/dd")}");
                      await widget.model!.checkPatientForRegistration(checkPatientForRegistrationModel);
                      GetPatientInfoRequestModel getPatientInfoRequestModel = GetPatientInfoRequestModel(
                        //TODO Elham* this return the static to dynamic
                        patientIdentificationID: "1062938285",
                        // _idController.text,
                        isHijri: 0,
                        isDentalAllowedBackend: false,
                        patientOutSA: 0,
                        generalid: GENERAL_ID,
                        sessionID: null,
                        dOB: "31/07/1988", //"${AppDateUtils.convertStringToDateFormat(_birthDate.toString(), "dd/MM/yyyy")}"
                      );
                      if (widget.model!.state == ViewState.ErrorLocal) {
                        Utils.showErrorToast(widget.model!.error);
                      } else {
                        await widget.model!.getPatientInfo(getPatientInfoRequestModel);
                        if (widget.model!.state == ViewState.ErrorLocal) {
                          Utils.showErrorToast(widget.model!.error);
                        } else {
                          widget.changePageViewIndex!(1);
                        }
                      }
                      GifLoaderDialogUtils.hideDialog(context);
                    }
                  },
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  isFormValid() {
    if (_phoneController.text != null && _phoneController.text.isNotEmpty && _idController.text != null && _idController.text.isNotEmpty && _birthDateInGregorian != null) {
      return true;
    }
    return false;
  }

  Future _selectDate(BuildContext context, DateTime dateTime, Function(dynamic) updateDate) async {
    if (calenderType == CalenderType.Hijri) {
      JDateModel hijriDate = JDateModel(dateTime: DateTime.now());
      final JPickerValue? pickedH = await showGlobalDatePicker(
        context: context,
        pickerType: PickerType.JHijri,
        startDate: birthDateInHijri ?? hijriDate,
        endDate: JDateModel(
          jhijri: JHijri(fDate: hijriDate.dateTime),
        ),

        // firstDate: new HijriCalendar()
        //   ..hYear = 1438
        //   ..hMonth = 12
        //   ..hDay = 25,
        pickerMode: DatePickerMode.day,
      );
      if (pickedH != null && birthDateInHijri != pickedH) updateDate(pickedH);
    } else {
      final DateTime? picked = await showDatePicker(
        context: context,
        initialDate: dateTime ?? DateTime.now(),
        firstDate: DateTime(DateTime.now().year - 150),
        lastDate: DateTime.now(),
        initialEntryMode: DatePickerEntryMode.calendar,
      );
      if (picked != null && picked != dateTime) {
        updateDate(picked);
      }
    }
  }

  void openListDialogField(String attributeName, String attributeValueId, List<dynamic> list, Function(dynamic selectedValue) okFunction) {
    ListSelectDialog dialog = ListSelectDialog(
      list: list,
      attributeName: attributeName,
      attributeValueId: attributeValueId,
      usingSearch: true,
      okText: TranslationBase.of(context).ok,
      okFunction: (selectedValue) {
        okFunction(selectedValue);
      },
    );
    showDialog(
      barrierDismissible: false,
      context: context,
      builder: (BuildContext context) {
        return dialog;
      },
    );
  }

  getBirthdate() {
    if (calenderType == CalenderType.Hijri) {
      return birthDateInHijri != null ? "$birthDateInHijri" : null;
    } else {
      return _birthDateInGregorian != null ? "${AppDateUtils.convertStringToDateFormat(_birthDateInGregorian.toString(), "yyyy/MM/dd")}" : null;
    }
  }
}
