import 'package:doctor_app_flutter/config/shared_pref_kay.dart';
import 'package:doctor_app_flutter/models/patient/patient_model.dart';
import 'package:doctor_app_flutter/providers/project_provider.dart';
import 'package:doctor_app_flutter/routes.dart';
import 'package:doctor_app_flutter/util/dr_app_shared_pref.dart';
import 'package:doctor_app_flutter/util/helpers.dart';
import 'package:flutter/services.dart';

import '../../config/size_config.dart';
import '../../widgets/shared/app_buttons_widget.dart';
import '../../widgets/shared/app_scaffold_widget.dart';
import '../../widgets/shared/app_text_form_field.dart';
import '../../widgets/shared/app_texts_widget.dart';
import '../../widgets/shared/rounded_container_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

import '../../lookups/patient_lookup.dart';
import '../../widgets/patients/dynamic_elements.dart';
import '../../config/config.dart';
import '../../models/doctor/doctor_profile_model.dart';
import 'package:doctor_app_flutter/util/translations_delegate_base.dart';
import 'package:provider/provider.dart';

DrAppSharedPreferances sharedPref = new DrAppSharedPreferances();
Helpers helpers = Helpers();

// OWNER : Ibrahim albitar
// DATE : 19-04-2020
// DESCRIPTION : Patient Search Screen.

class PatientSearchScreen extends StatefulWidget {
  @override
  _PatientSearchScreenState createState() => _PatientSearchScreenState();
}

class _PatientSearchScreenState extends State<PatientSearchScreen> {
  String _selectedType = '1';
  String _selectedLocation = '1';
  String error = '';
  ProjectProvider projectsProvider;
  String itemText = '';
  String itemText2 = '';
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  bool _autoValidate = false;

  var _patientSearchFormValues = PatientModel(
      FirstName: "0",
      MiddleName: "0",
      LastName: "0",
      PatientMobileNumber: "0",
      PatientIdentificationID: "0",
      PatientID: 0,
      From: "0",
      To: "0",
      LanguageID: 2,
      stamp: "2020-03-02T13:56:39.170Z",
      IPAdress: "11.11.11.11",
      VersionID: 1.2,
      Channel: 9,
      TokenID: "2Fi7HoIHB0eDyekVa6tCJg==",
      SessionID: "5G0yXn0Jnq",
      IsLoginForDoctorApp: true,
      PatientOutSA: false);

  void _validateInputs() async {
//print("============== _selectedType============"+ _selectedType);

    try {
      //====================
      //_selectedType=='3'?
      //=====================

      Map profile = await sharedPref.getObj(DOCTOR_PROFILE);
      DoctorProfileModel doctorProfile =
          new DoctorProfileModel.fromJson(profile);
      if (_formKey.currentState.validate()) {
        _formKey.currentState.save();

        sharedPref.setString(SLECTED_PATIENT_TYPE, _selectedType);
        print('************_selectedType*************');
        print('_selectedType${_selectedType}');
        String token = await sharedPref.getString(TOKEN);

        _patientSearchFormValues.TokenID = token;
        _patientSearchFormValues.ProjectID = doctorProfile.projectID; //15
        _patientSearchFormValues.DoctorID = doctorProfile.doctorID;
        _patientSearchFormValues.ClinicID = doctorProfile.clinicID;
        //=====================
        // _patientSearchFormValues.
        //=====================

        print("=============doctorProfile.clinicID=" +
            doctorProfile.clinicID.toString());

        Navigator.of(context).pushNamed(PATIENTS, arguments: {
          "patientSearchForm": _patientSearchFormValues,
          "selectedType": _selectedType
        });
      } else {
        setState(() {
          _autoValidate = true;
        });
      }
    } catch (err) {
      error = err;
      // handelCatchErrorCase(err);
    }
  }

  handelCatchErrorCase(err) {
    //isLoading = false;
    //isError = true;
    error = helpers.generateContactAdminMsg(err);
    //notifyListeners();
    throw err;
  }

  @override
  Widget build(BuildContext context) {
    projectsProvider = Provider.of(context);
    return AppScaffold(
        appBarTitle: TranslationBase.of(context).searchPatient,
        body: ListView(
          children: <Widget>[
            RoundedContainer(
              child: Column(
                children: <Widget>[
                  Icon(
                    Icons.search,
                    size: SizeConfig.imageSizeMultiplier * 15,
                  ),
                  Container(
                    padding: EdgeInsets.all(15),
                    width: SizeConfig.screenWidth * 1,
                    child: Form(
                      key: _formKey,
                      autovalidate: _autoValidate,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          SizedBox(
                            height: 5,
                          ),
                          Container(
                            decoration: ShapeDecoration(
                              shape: RoundedRectangleBorder(
                                side: BorderSide(
                                    width: 1.0,
                                    style: BorderStyle.solid,
                                    color: Color(0xff707070)),
                                borderRadius:
                                    BorderRadius.all(Radius.circular(5.0)),
                              ),
                            ),
                            // margin: 0,
                            // showBorder: true,
                            // raduis: 30,
                            // borderColor: Color(0xff707070),
                            width: double.infinity,
                            child: Padding(
                              padding: EdgeInsets.only(
                                  top: SizeConfig.widthMultiplier * 0.9,
                                  bottom: SizeConfig.widthMultiplier * 0.9,
                                  right: SizeConfig.widthMultiplier * 3,
                                  left: SizeConfig.widthMultiplier * 3),
                              child: Row(
                                mainAxisSize: MainAxisSize.max,
                                children: <Widget>[
                                  Expanded(
                                    // add Expanded to have your dropdown button fill remaining space
                                    child: DropdownButtonHideUnderline(
                                        child: DropdownButton(
                                      isExpanded: true,
                                      value: _selectedType,
                                      iconSize: 40,
                                      elevation: 16,
                                      selectedItemBuilder:
                                          (BuildContext context) {
                                        return PATIENT_TYPE.map((item) {
                                          return Row(
                                            mainAxisSize: MainAxisSize.max,
                                            children: <Widget>[
                                              !projectsProvider.isArabic
                                                  ? AppText(
                                                      item['text'],
                                                      fontSize: SizeConfig
                                                              .textMultiplier *
                                                          2.1,
                                                    )
                                                  : AppText(
                                                      item['text_ar'],
                                                      fontSize: SizeConfig
                                                              .textMultiplier *
                                                          2.1,
                                                    ),
                                            ],
                                          );
                                        }).toList();
                                      },
                                      onChanged: (String newValue) => {
                                        setState(() {
                                          _selectedType = newValue;
                                          selectedPatientType =
                                              int.parse(_selectedType);
                                        })
                                      },
                                      items: PATIENT_TYPE.map((item) {
                                        !projectsProvider.isArabic
                                            ? itemText = item['text']
                                            : itemText = item['text_ar'];
                                        return DropdownMenuItem(
                                          child: Text(
                                            itemText,
                                            textAlign: TextAlign.end,
                                          ),
                                          value: item['val'],
                                        );
                                      }).toList(),
                                    )),
                                  ),
                                ],
                              ),
                            ),
                          ),
                          SizedBox(
                            height: 10,
                          ),
                          AppTextFormField(
                              hintText: TranslationBase.of(context).firstName,
                              onSaved: (value) {
                                value == null
                                    ? _patientSearchFormValues.setFirstName =
                                        "0"
                                    : _patientSearchFormValues.setFirstName =
                                        value;

                                if (value.toString().trim().isEmpty) {
                                  _patientSearchFormValues.setFirstName = "0";
                                }
                              },
                              // validator: (value) {
                              //   return TextValidator().validateName(value);
                              // },
                              inputFormatter: ONLY_LETTERS),
                          SizedBox(
                            height: 10,
                          ),
                          AppTextFormField(
                              hintText: TranslationBase.of(context).middleName,
                              onSaved: (value) {
                                value == null
                                    ? _patientSearchFormValues.setMiddleName =
                                        "0"
                                    : _patientSearchFormValues.setMiddleName =
                                        value;
                                if (value.toString().trim().isEmpty) {
                                  _patientSearchFormValues.setMiddleName = "0";
                                }
                              },
                              // validator: (value) {
                              //   return TextValidator().validateName(value);
                              // },
                              inputFormatter: ONLY_LETTERS),
                          SizedBox(
                            height: 10,
                          ),
                          AppTextFormField(
                              hintText: TranslationBase.of(context).lastName,
                              onSaved: (value) {
                                value == null
                                    ? _patientSearchFormValues.setLastName = "0"
                                    : _patientSearchFormValues.setLastName =
                                        value;
                                if (value.toString().trim().isEmpty) {
                                  _patientSearchFormValues.setLastName = "0";
                                }
                              },
                              inputFormatter: ONLY_LETTERS),
                          SizedBox(
                            height: 10,
                          ),
                          AppTextFormField(
                            textInputType: TextInputType.number,
                            hintText: TranslationBase.of(context).phoneNumber,
                            // validator: (value) {
                            //   return TextValidator().validateMobile(value);
                            // },
                            inputFormatter: ONLY_NUMBERS,
                            onSaved: (value) {
                              value == null
                                  ? _patientSearchFormValues
                                      .setPatientMobileNumber = "0"
                                  : _patientSearchFormValues
                                      .setPatientMobileNumber = value;

                              if (value.toString().trim().isEmpty) {
                                _patientSearchFormValues
                                    .setPatientMobileNumber = "0";
                              }
                            },
                          ),
                          SizedBox(
                            height: 10,
                          ),
                          AppTextFormField(
                              textInputType: TextInputType.number,
                              hintText: TranslationBase.of(context).patientID,
                              //
                              inputFormatter: ONLY_NUMBERS,
                              onSaved: (value) {
                                // _patientSearchFormValues.PatientID = 89000;

                                value == null
                                    ? _patientSearchFormValues.setPatientID = 0
                                    : _patientSearchFormValues.setPatientID =
                                        int.parse(value);
                                if (value.toString().trim().isEmpty) {
                                  _patientSearchFormValues.setPatientID = 0;
                                }
                              }),
                          SizedBox(
                            height: 10,
                          ),
                          AppTextFormField(
                            textInputType: TextInputType.number,
                            hintText: TranslationBase.of(context).patientFile,
                            // validator: (value) {
                            //   return TextValidator().validateIdNumber(value);
                            // },
                            inputFormatter: ONLY_NUMBERS,
                            onSaved: (value) {
                              //_patientSearchFormValues. = value;
                            },
                          ),
                          (!(_selectedType == '2' || _selectedType == '4'))
                              ? DynamicElements(_patientSearchFormValues)
                              : SizedBox(
                                  height: 0,
                                ),
                          SizedBox(
                            height: 10,
                          ),
                          Container(
                            // margin: 0,
                            // showBorder: true,
                            // raduis: 30,
                            // borderColor: Color(0xff707070),
                            decoration: ShapeDecoration(
                              shape: RoundedRectangleBorder(
                                side: BorderSide(
                                    width: 1.0,
                                    style: BorderStyle.solid,
                                    color: Color(0xff707070)),
                                borderRadius:
                                    BorderRadius.all(Radius.circular(5.0)),
                              ),
                            ),
                            width: double.infinity,
                            child: Padding(
                              padding: EdgeInsets.only(
                                  top: SizeConfig.widthMultiplier * 0.9,
                                  bottom: SizeConfig.widthMultiplier * 0.9,
                                  right: SizeConfig.widthMultiplier * 3,
                                  left: SizeConfig.widthMultiplier * 3),
                              child: Row(
                                mainAxisSize: MainAxisSize.max,
                                children: <Widget>[
                                  Expanded(
                                    // add Expanded to have your dropdown button fill remaining space
                                    child: DropdownButtonHideUnderline(
                                        child: DropdownButton(
                                      isExpanded: true,
                                      value: _selectedLocation,
                                      iconSize: 40,
                                      elevation: 16,
                                      selectedItemBuilder:
                                          (BuildContext context) {
                                        return LOCATIONS.map((item) {
                                          return Row(
                                            mainAxisSize: MainAxisSize.max,
                                            children: <Widget>[
                                              !projectsProvider.isArabic
                                                  ? AppText(
                                                      item['text'],
                                                      fontSize: SizeConfig
                                                              .textMultiplier *
                                                          2.1,
                                                    )
                                                  : AppText(
                                                      item['text-ar'],
                                                      fontSize: SizeConfig
                                                              .textMultiplier *
                                                          2.1,
                                                    )
                                            ],
                                          );
                                        }).toList();
                                      },
                                      onChanged: (String newValue) => {
                                        setState(() {
                                          _selectedLocation = newValue;
                                        })
                                      },
                                      items: LOCATIONS.map((item) {
                                        !projectsProvider.isArabic
                                            ? itemText2 = item['text']
                                            : itemText2 = item['text-ar'];
                                        return DropdownMenuItem(
                                          child: Text(
                                            itemText2,
                                            textAlign: TextAlign.end,
                                          ),
                                          value: item['val'],
                                        );
                                      }).toList(),
                                    )),
                                  ),
                                ],
                              ),
                            ),
                          ),
                          Container(
                              child: Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  children: <Widget>[
                                Checkbox(
                                    value: true,
                                    activeColor: Color(0xffFFDDD9),
                                    onChanged: (bool newValue) {}),
                                AppText(
                                    TranslationBase.of(context)
                                        .onlyArrivedPatient,
                                    fontSize: SizeConfig.textMultiplier * 2),
                              ])),
                          SizedBox(
                            height: 10,
                          ),
                        ],
                      ),
                    ),
                  )
                ],
              ),
            ),
            Container(
              margin: EdgeInsets.all(SizeConfig.widthMultiplier * 5),
              child: Wrap(
                alignment: WrapAlignment.center,
                children: <Widget>[
                  AppButton(
                    title: TranslationBase.of(context).search,
                    color: Color(0xff58434F),
                    onPressed: () {
                      _validateInputs();
                    },
                  ),
                ],
              ),
            )
          ],
        ));
  }
}
