import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/models/Appointments/DentalChiefComplaintsModel.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/doctor_response_mapper.dart';
import 'package:hmg_patient_app/services/clinic_services/get_clinic_service.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/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

// ignore: must_be_immutable
class DentalComplaintCard extends StatefulWidget {
  final ListDentalChiefComplain listDentalChiefComplain;
  late Function logAnalytics;
  var languageID;
  Function? onSelectedMethod;
  bool isDoctorNameSearch;
  bool isFromHospitalSearchPage;
  Function(RegionList)? onDoctorFetched;

  DentalComplaintCard({required this.listDentalChiefComplain,
    this.languageID,
    this.onSelectedMethod,
    this.isDoctorNameSearch = false,
    this.isFromHospitalSearchPage = false,
    this.onDoctorFetched});

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

class _DentalComplaintCardState extends State<DentalComplaintCard> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: InkWell(
        onTap: () {
          if (widget.logAnalytics != null) widget.logAnalytics();
          // if(widget.isDoctorNameSearch) {
          //   widget.onSelectedMethod();
          // } else {
          if (widget.isFromHospitalSearchPage) {
            getChiefComplaintsDoctorMappedList();
          } else
            getChiefComplaintsList();
          // }
        },
        child: Container(
          width: double.infinity,
          padding: EdgeInsets.all(14.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.max,
            children: <Widget>[
              Container(
                child: Text(
                  widget.listDentalChiefComplain!.name!,
                  style: TextStyle(
                    fontSize: 16.0,
                    color: Colors.black,
                    letterSpacing: -0.64,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  getChiefComplaintsList() {
    int languageID = Provider.of<ProjectViewModel>(context, listen: false).isArabic ? 1 : 2;
    List<DoctorList> doctorsList = [];
    List<PatientDoctorAppointmentList> _patientDoctorAppointmentListHospital = [];

    GifLoaderDialogUtils.showMyDialog(context);
    ClinicListService service = new ClinicListService();
    service.getChiefComplaintDoctorList(widget.listDentalChiefComplain!.iD!, widget.listDentalChiefComplain.projectID!, languageID, context).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (res['MessageStatus'] == 1) {
        print(res['List_DentalDoctorChiefComplaintMapping']);
        setState(() {
          doctorsList.clear();
          res['List_DentalDoctorChiefComplaintMapping'].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(),
                  projectTopName: element.projectTopName,
                  projectBottomName: element.projectBottomName,
                  patientDoctorAppointment: element));
            }
          });
          navigateToSearchResults(context, doctorsList, _patientDoctorAppointmentListHospital);
        });
      } else {
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
    });
  }

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

  void getChiefComplaintsDoctorMappedList() {
    var isArabic = context.read<ProjectViewModel>().isArabic;
    int languageID =
        Provider.of<ProjectViewModel>(context, listen: false).isArabic ? 1 : 2;
    List<DoctorList> doctorsList = [];
    List<PatientDoctorAppointmentList> _patientDoctorAppointmentListHospital =
        [];

    GifLoaderDialogUtils.showMyDialog(context);
    ClinicListService service = new ClinicListService();
    service
        .getChiefComplaintDoctorList(widget.listDentalChiefComplain!.iD!,
            widget.listDentalChiefComplain.projectID!, languageID, context)
        .then((res) async {
      GifLoaderDialogUtils.hideDialog(context);
      if (res['MessageStatus'] == 1) {
        RegionList regionHospitalList = RegionList();
        print(res['List_DentalDoctorChiefComplaintMapping']);
        setState(() async {
          doctorsList.clear();
          res['List_DentalDoctorChiefComplaintMapping'].forEach((v) {
            doctorsList.add(new DoctorList.fromJson(v));
          });

          regionHospitalList = await DoctorMapper.getMappedDoctor(doctorsList,
              isArabic: isArabic);
          widget.onDoctorFetched?.call(regionHospitalList);
        });
      } else {
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
    });
  }
}
