import 'package:hmg_patient_app/core/model/hospitals/hospitals_model.dart';
import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/pages/ErService/EROnlineCheckIn/EROnlineCheckInPaymentDetails.dart';
import 'package:hmg_patient_app/services/clinic_services/get_clinic_service.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/translations_delegate_base.dart';
import 'package:hmg_patient_app/uitl/utils_new.dart';
import 'package:hmg_patient_app/widgets/buttons/defaultButton.dart';
import 'package:hmg_patient_app/widgets/others/app_scaffold_widget.dart';
import 'package:hmg_patient_app/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class EROnlineCheckInBookAppointment extends StatefulWidget {
  const EROnlineCheckInBookAppointment();

  @override
  State<EROnlineCheckInBookAppointment> createState() => _EROnlineCheckInBookAppointmentState();
}

class _EROnlineCheckInBookAppointmentState extends State<EROnlineCheckInBookAppointment> with SingleTickerProviderStateMixin {
  late ProjectViewModel projectViewModel;
  List<HospitalsModel> projectsList = [];
  final GlobalKey projectDropdownKey = GlobalKey();
  HospitalsModel? selectedHospital;
  String projectDropdownValue = "";

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getProjectsList();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);
    return AppScaffold(
      isShowAppBar: true,
      appBarTitle: TranslationBase.of(context).emergency + " ${TranslationBase.of(context).checkinOptions}",
      isShowDecPage: false,
      showNewAppBar: true,
      showNewAppBarTitle: true,
      backgroundColor: Color(0xffF8F8F8),
      body: Padding(
        padding: EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            InkWell(
              onTap: () {
                openDropdown(projectDropdownKey);
              },
              child: Container(
                width: double.infinity,
                decoration: containerRadius(Colors.white, 12),
                padding: EdgeInsets.only(left: 10, right: 10, top: 12, bottom: 12),
                child: Row(
                  children: [
                    Flexible(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            TranslationBase.of(context).selectHospital,
                            style: TextStyle(
                              fontSize: 11,
                              letterSpacing: -0.44,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                          Container(
                            height: 18,
                            child: DropdownButtonHideUnderline(
                              child: DropdownButton<HospitalsModel>(
                                key: projectDropdownKey,
                                hint: new Text(TranslationBase.of(context).selectHospital),
                                value: selectedHospital,
                                iconSize: 0,
                                isExpanded: true,
                                style: TextStyle(fontSize: 14, letterSpacing: -0.56, color: Colors.black),
                                items: projectsList.map((item) {
                                  return new DropdownMenuItem<HospitalsModel>(
                                    value: item,
                                    child: new Text(item.name! + " - " + item.distanceInKilometers.toString() + " " + TranslationBase.of(context).km),
                                  );
                                }).toList(),
                                onChanged: (newValue) async {
                                  setState(() {
                                    selectedHospital = newValue;
                                    projectDropdownValue = newValue!.mainProjectID.toString();
                                  });
                                },
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Icon(Icons.keyboard_arrow_down),
                  ],
                ),
              ),
            ),
            mHeight(16),
            Container(
              width: double.infinity,
              decoration: containerRadius(Colors.white, 12),
              padding: EdgeInsets.only(left: 10, right: 10, top: 12, bottom: 12),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    TranslationBase.of(context).clinicName,
                    style: TextStyle(
                      fontSize: 11,
                      letterSpacing: -0.44,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  Text(
                    "ER Clinic",
                    style: TextStyle(fontSize: 14, letterSpacing: -0.56, color: Colors.black),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
      bottomSheet: Container(
        height: 80,
        color: CustomColors.white,
        padding: EdgeInsets.fromLTRB(12.0, 12.0, 12.0, 25.0),
        child: DefaultButton(
          TranslationBase.of(context).bookAppo,
          () {
            if (projectDropdownValue == "" || selectedHospital == null) {
              AppToast.showErrorToast(message: TranslationBase.of(context).selectHospital);
            } else {
              Navigator.push(
                context,
                FadePage(
                  page: EROnlineCheckInPaymentDetails(
                    projectID: selectedHospital!.iD,
                    isERBookAppointment: true,
                    projectName: selectedHospital!.name ?? "",
                  ),
                ),
              );
            }
          },
          color: CustomColors.accentColor,
        ),
      ),
    );
  }

  getProjectsList() {
    int languageID = projectViewModel.isArabic ? 1 : 2;
    GifLoaderDialogUtils.showMyDialog(context);
    ClinicListService service = new ClinicListService();
    List<HospitalsModel> projectsListLocal = [];
    service.getProjectsList(languageID, context).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (res['MessageStatus'] == 1) {
        setState(() {
          res['ListProject'].forEach((v) {
            projectsListLocal.add(new HospitalsModel.fromJson(v));
          });
          projectsList = projectsListLocal;
        });
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
    });
  }

  void openDropdown(GlobalKey key) {
    GestureDetector? detector;
    void searchForGestureDetector(BuildContext element) {
      element.visitChildElements((element) {
        if (element.widget != null && element.widget is GestureDetector) {
          detector = element.widget as GestureDetector?;
          // return false;
        } else {
          searchForGestureDetector(element);
        }
        // return true;
      });
    }

    searchForGestureDetector(key.currentContext!);
    assert(detector != null);
    detector!.onTap!();
  }
}
