import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/models/Appointments/DoctorListResponse.dart';
import 'package:diplomaticquarterapp/services/appointment_services/GetDoctorsList.dart';
import 'package:diplomaticquarterapp/theme/colors.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../SearchResults.dart';

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

class _SearchByDoctorState extends State<SearchByDoctor> {
  TextEditingController doctorNameController = new TextEditingController();
  bool _isButtonDisabled;
  ProjectViewModel projectViewModel;

  @override
  void initState() {
    super.initState();
    _isButtonDisabled = true;
  }

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(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: RaisedButton(
          color: CustomColors.accentColor,
          textColor: Colors.white,
          disabledTextColor: Colors.white,
          elevation: 0,
          disabledColor: new Color(0xFFbcc2c4),
          onPressed: () {
            if (_isButtonDisabled == false) {
              _searchDoctor(context);
            }
          },
          child: Text(TranslationBase.of(context).search, style: TextStyle(fontSize: 18.0)),
        ),
      ),
    );
  }

  getDoctorsList(BuildContext context) {
    GifLoaderDialogUtils.showMyDialog(context);
    List<DoctorList> doctorsList = [];
    DoctorsListService service = new DoctorsListService();

    List<PatientDoctorAppointmentList> _patientDoctorAppointmentListHospital = List();

    service.getDoctorsListByName(doctorNameController.text, 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.projectName).toList();

              if (doctorByHospital.length != 0) {
                _patientDoctorAppointmentListHospital[_patientDoctorAppointmentListHospital.indexOf(doctorByHospital[0])].patientDoctorAppointmentList.add(element);
              } else {
                _patientDoctorAppointmentListHospital
                    .add(PatientDoctorAppointmentList(filterName: element.projectName, distanceInKMs: element.projectDistanceInKiloMeters.toString(), patientDoctorAppointment: element));
              }
            });
          } 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) {
    projectViewModel.analytics.appointment.book_appointment_doctor_search(query: doctorNameController.text);
    getDoctorsList(context);
  }

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

  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),
          ],
        ),
      ),
    );
  }
}
