import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/models/Appointments/DoctorListResponse.dart';
import 'package:hmg_patient_app/pages/BookAppointment/SearchResults.dart';
import 'package:hmg_patient_app/services/appointment_services/GetDoctorsList.dart';
import 'package:hmg_patient_app/theme/colors.dart';
import 'package:hmg_patient_app/uitl/app_toast.dart';
import 'package:hmg_patient_app/uitl/gif_loader_dialog_utils.dart';
import 'package:hmg_patient_app/uitl/location_util.dart';
import 'package:hmg_patient_app/uitl/translations_delegate_base.dart';
import 'package:hmg_patient_app/widgets/buttons/custom_text_button.dart';
import 'package:hmg_patient_app/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class SearchByDoctor extends StatefulWidget {
  @override
  _SearchByDoctorState createState() => _SearchByDoctorState();
}

class _SearchByDoctorState extends State<SearchByDoctor> {
  TextEditingController doctorNameController = new TextEditingController();
  late bool _isButtonDisabled;
  late LocationUtils locationUtils;

  @override
  void initState() {
    super.initState();
    locationUtils =
        new LocationUtils(isShowConfirmDialog: true, context: context);
    locationUtils.getCurrentLocation();
    _isButtonDisabled = true;
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Expanded(
          child: Container(
            margin: EdgeInsets.all(20.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.max,
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(top: 10.0, bottom: 15.0),
                  child: Text(
                    TranslationBase.of(context).searchByDocText,
                    style: TextStyle(
                      fontSize: 14.0,
                      letterSpacing: -0.9,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),
                inputWidget(TranslationBase.of(context).enterDocName, '',
                    doctorNameController),
              ],
            ),
          ),
        ),
        _buildCounterButton(),
      ],
    );
  }

  Widget _buildCounterButton() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(16),
      color: Colors.white,
      child: new ButtonTheme(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(10.0),
        ),
        minWidth: MediaQuery.of(context).size.width,
        height: 45.0,
        child: CustomTextButton(
          backgroundColor: CustomColors.accentColor,
          elevation: 0,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(6),
          ),
          onPressed: () {
            if (_isButtonDisabled == false) {
              FocusManager.instance.primaryFocus?.unfocus();
              _searchDoctor(context);
            }
          },
          child: Text(TranslationBase.of(context).search,
              style: TextStyle(fontSize: 18.0, color: Colors.white)),
        ),
      ),
    );
  }

  getDoctorsList(BuildContext context) {
    int languageID = context.read<ProjectViewModel>().isArabic ? 1 : 2;
    GifLoaderDialogUtils.showMyDialog(context);
    List<DoctorList> doctorsList = [];
    DoctorsListService service = new DoctorsListService();

    List<PatientDoctorAppointmentList> _patientDoctorAppointmentListHospital =
        [];

    service
        .getDoctorsListByName(doctorNameController.text, languageID, context)
        .then((res) {
      //   GifLoaderDialogUtils.hideDialog(context);
      if (res['MessageStatus'] == 1) {
        setState(() {
          if (res['DoctorList'].length != 0) {
            res['DoctorList'].forEach((v) {
              doctorsList.add(new DoctorList.fromJson(v));
            });

            doctorsList.forEach((element) {
              List<PatientDoctorAppointmentList> doctorByHospital =
                  _patientDoctorAppointmentListHospital
                      .where((elementClinic) =>
                          elementClinic.filterName ==
                          element.getProjectCompleteName())
                      .toList();

              if (doctorByHospital.length != 0) {
                _patientDoctorAppointmentListHospital[
                        _patientDoctorAppointmentListHospital
                            .indexOf(doctorByHospital[0])]
                    .patientDoctorAppointmentList!
                    .add(element);
              } else {
                _patientDoctorAppointmentListHospital.add(
                    PatientDoctorAppointmentList(
                        filterName: element.getProjectCompleteName(),
                        distanceInKMs:
                            element.projectDistanceInKiloMeters.toString(),
                        projectTopName: element.projectTopName,
                        projectBottomName: element.projectBottomName,
                  patientDoctorAppointment: element,
                  isHMC: element.isHMC,
                ));
              }
            });
          } else {
            GifLoaderDialogUtils.hideDialog(context);
            AppToast.showErrorToast(message: res['ErrorSearchMsg']);
          }
        });
        GifLoaderDialogUtils.hideDialog(context);
        navigateToSearchResults(
            context, doctorsList, _patientDoctorAppointmentListHospital);
      } else {
        GifLoaderDialogUtils.hideDialog(context);
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
  }

  _onDocTextChanged(content) {
    print(content);
    if (content.length >= 3) {
      setState(() {
        _isButtonDisabled = false;
      });
    } else {
      setState(() {
        _isButtonDisabled = true;
      });
    }
    print(_isButtonDisabled);
  }

  _searchDoctor(BuildContext context) {
    getDoctorsList(context);
    context
        .read<ProjectViewModel>()
        .analytics
        .appointment
        .book_appointment_doctor_search(query: doctorNameController.text);
  }

  navigateToSearchResults(context, List<DoctorList> docList,
      List<PatientDoctorAppointmentList> patientDoctorAppointmentListHospital) {
    Navigator.push(
        context,
        FadePage(
            page: SearchResults(
          isLiveCareAppointment: false,
          isDoctorNameSearch: true,
          doctorsList: docList,
          patientDoctorAppointmentListHospital:
              patientDoctorAppointmentListHospital,
          isDoctorSearchResult: true,
        )));
  }

  Widget inputWidget(
      String _labelText, String _hintText, TextEditingController _controller,
      {String? prefix, bool isEnable = true, bool hasSelection = false}) {
    return Container(
      padding: EdgeInsets.only(left: 16, right: 16, bottom: 15, top: 15),
      alignment: Alignment.center,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(15),
        color: Colors.white,
        border: Border.all(
          color: Color(0xffefefef),
          width: 1,
        ),
      ),
      child: InkWell(
        onTap: hasSelection ? () {} : null,
        child: Row(
          children: [
            Expanded(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    _labelText,
                    style: TextStyle(
                      fontSize: 11,
                      fontWeight: FontWeight.w600,
                      color: Color(0xff2B353E),
                      letterSpacing: -0.44,
                    ),
                  ),
                  TextField(
                    enabled: isEnable,
                    scrollPadding: EdgeInsets.zero,
                    keyboardType: TextInputType.text,
                    controller: _controller,
                    onChanged: (value) => {_onDocTextChanged(value)},
                    style: TextStyle(
                      fontSize: 14,
                      height: 21 / 14,
                      fontWeight: FontWeight.w400,
                      color: Color(0xff2B353E),
                      letterSpacing: -0.44,
                    ),
                    decoration: InputDecoration(
                      isDense: true,
                      hintText: _hintText,
                      hintStyle: TextStyle(
                        fontSize: 14,
                        height: 21 / 14,
                        fontWeight: FontWeight.w400,
                        color: Color(0xff575757),
                        letterSpacing: -0.56,
                      ),
                      prefixIconConstraints: BoxConstraints(minWidth: 50),
                      prefixIcon: prefix == null
                          ? null
                          : Text(
                              "+" + prefix,
                              style: TextStyle(
                                fontSize: 14,
                                height: 21 / 14,
                                fontWeight: FontWeight.w500,
                                color: Color(0xff2E303A),
                                letterSpacing: -0.56,
                              ),
                            ),
                      contentPadding: EdgeInsets.zero,
                      border: InputBorder.none,
                      focusedBorder: InputBorder.none,
                      enabledBorder: InputBorder.none,
                    ),
                  ),
                ],
              ),
            ),
            if (hasSelection) Icon(Icons.keyboard_arrow_down_outlined),
          ],
        ),
      ),
    );
  }
}
