import 'dart:async';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:hmg_patient_app_new/core/app_assets.dart';
import 'package:hmg_patient_app_new/core/app_state.dart';
import 'package:hmg_patient_app_new/core/dependencies.dart';
import 'package:hmg_patient_app_new/core/utils/size_utils.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/extensions/string_extensions.dart';
import 'package:hmg_patient_app_new/extensions/widget_extensions.dart';
import 'package:hmg_patient_app_new/features/book_appointments/book_appointments_view_model.dart';
import 'package:hmg_patient_app_new/features/book_appointments/models/resp_models/get_clinic_list_response_model.dart';
import 'package:hmg_patient_app_new/features/book_appointments/models/resp_models/get_livecare_clinics_response_model.dart';
import 'package:hmg_patient_app_new/features/my_appointments/appointment_via_region_viewmodel.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/appointments/widgets/faculity_selection/facility_type_selection_widget.dart';
import 'package:hmg_patient_app_new/presentation/appointments/widgets/hospital_bottom_sheet/hospital_bottom_sheet_body.dart';
import 'package:hmg_patient_app_new/presentation/appointments/widgets/region_bottomsheet/region_list_widget.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/dental_chief_complaints_page.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/laser/laser_appointment.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/select_doctor_page.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/select_livecare_clinic_page.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/widgets/clinic_card.dart';
import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart';
import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart';
import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart';
import 'package:hmg_patient_app_new/widgets/input_widget.dart';
import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart';
import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart';
import 'package:hmg_patient_app_new/widgets/transitions/fade_page.dart';
import 'package:provider/provider.dart';

class SelectClinicPage extends StatefulWidget {
  bool isFromRegionFlow;

  SelectClinicPage({super.key, this.isFromRegionFlow = false});

  @override
  State<SelectClinicPage> createState() => _SelectClinicPageState();
}

class _SelectClinicPageState extends State<SelectClinicPage> {
  TextEditingController searchEditingController = TextEditingController();
  FocusNode textFocusNode = FocusNode();
  late AppointmentViaRegionViewmodel regionalViewModel;
  late AppState appState;
  late BookAppointmentsViewModel bookAppointmentsViewModel;

  @override
  void initState() {
    scheduleMicrotask(() {
      bookAppointmentsViewModel.getClinics();
    });
    super.initState();
  }

  @override
  void dispose() {
    textFocusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    bookAppointmentsViewModel = Provider.of<BookAppointmentsViewModel>(context, listen: false);
    regionalViewModel = Provider.of<AppointmentViaRegionViewmodel>(context, listen: true);
    appState = getIt.get<AppState>();
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: CollapsingListView(
        title: bookAppointmentsViewModel.isLiveCareSchedule ? "Select LiveCare Clinic".needTranslation : LocaleKeys.selectClinic.tr(context: context),
        child: SingleChildScrollView(
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 24.h),
            child: Consumer<BookAppointmentsViewModel>(builder: (context, bookAppointmentsVM, child) {
              return Column(
                children: [
                  SizedBox(height: 16.h),
                  TextInputWidget(
                    labelText: LocaleKeys.search.tr(context: context),
                    hintText: LocaleKeys.clinicName.tr(context: context),
                    controller: searchEditingController,
                    isEnable: true,
                    prefix: null,
                    autoFocus: false,
                    isBorderAllowed: false,
                    keyboardType: TextInputType.text,
                    focusNode: textFocusNode,
                    suffix: searchEditingController.text.isNotEmpty
                        ? GestureDetector(
                            onTap: () {
                              searchEditingController.clear();
                              bookAppointmentsViewModel.filterClinics("");
                              textFocusNode.unfocus();
                            },
                            child: Utils.buildSvgWithAssets(icon: AppAssets.close_bottom_sheet_icon, width: 20.h, height: 20.h, fit: BoxFit.scaleDown),
                          )
                        : null,
                    onChange: (value) {
                      bookAppointmentsViewModel.filterClinics(value!);
                    },
                    padding: EdgeInsets.symmetric(
                      vertical: ResponsiveExtension(10).h,
                      horizontal: ResponsiveExtension(15).h,
                    ),
                  ),
                  bookAppointmentsVM.isLiveCareSchedule
                      ? ListView.separated(
                          padding: EdgeInsets.only(top: 24.h),
                          shrinkWrap: true,
                          physics: NeverScrollableScrollPhysics(),
                          itemCount: bookAppointmentsVM.isClinicsListLoading ? 5 : bookAppointmentsVM.liveCareClinicsList.length,
                          itemBuilder: (context, index) {
                            return bookAppointmentsVM.isClinicsListLoading
                                ? ClinicCard(
                                    bookAppointmentsVM: bookAppointmentsVM,
                                    liveCareClinicsResponseModel: GetLiveCareClinicsResponseModel(),
                                    clinicsListResponseModel: GetClinicsListResponseModel(),
                                    isLoading: bookAppointmentsVM.isClinicsListLoading,
                                  )
                                : AnimationConfiguration.staggeredList(
                                    position: index,
                                    duration: const Duration(milliseconds: 500),
                                    child: SlideAnimation(
                                      verticalOffset: 100.0,
                                      child: FadeInAnimation(
                                        child: AnimatedContainer(
                                          duration: Duration(milliseconds: 300),
                                          curve: Curves.easeInOut,
                                          decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.h, hasShadow: true),
                                          child: ClinicCard(
                                            bookAppointmentsVM: bookAppointmentsVM,
                                            liveCareClinicsResponseModel: bookAppointmentsVM.liveCareClinicsList[index],
                                            clinicsListResponseModel: GetClinicsListResponseModel(),
                                            isLoading: bookAppointmentsVM.isClinicsListLoading,
                                          ).onPress(() {
                                            onLiveCareClinicSelected(bookAppointmentsVM.liveCareClinicsList[index]);
                                          }),
                                        ),
                                      ),
                                    ),
                                  );
                          },
                          separatorBuilder: (BuildContext cxt, int index) => SizedBox(height: 16.h),
                        )
                      : ListView.separated(
                          padding: EdgeInsets.only(top: 24.h),
                          shrinkWrap: true,
                          physics: NeverScrollableScrollPhysics(),
                          itemCount: bookAppointmentsVM.isClinicsListLoading ? 5 : bookAppointmentsVM.filteredClinicsList.length,
                          itemBuilder: (context, index) {
                            return bookAppointmentsVM.isClinicsListLoading
                                ? ClinicCard(
                                    bookAppointmentsVM: bookAppointmentsVM,
                                    liveCareClinicsResponseModel: GetLiveCareClinicsResponseModel(),
                                    clinicsListResponseModel: GetClinicsListResponseModel(),
                                    isLoading: bookAppointmentsVM.isClinicsListLoading,
                                  )
                                : AnimationConfiguration.staggeredList(
                                    position: index,
                                    duration: const Duration(milliseconds: 500),
                                    child: SlideAnimation(
                                      verticalOffset: 100.0,
                                      child: FadeInAnimation(
                                        child: AnimatedContainer(
                                          duration: Duration(milliseconds: 300),
                                          curve: Curves.easeInOut,
                                          decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.h, hasShadow: true),
                                          child: ClinicCard(
                                            bookAppointmentsVM: bookAppointmentsVM,
                                            liveCareClinicsResponseModel: GetLiveCareClinicsResponseModel(),
                                            clinicsListResponseModel: bookAppointmentsVM.filteredClinicsList[index],
                                            isLoading: bookAppointmentsVM.isClinicsListLoading,
                                          ).onPress(() {
                                            onClinicSelected(bookAppointmentsVM.filteredClinicsList[index]);
                                          }),
                                        ),
                                      ),
                                    ),
                                  );
                          },
                          separatorBuilder: (BuildContext cxt, int index) => SizedBox(height: 16.h),
                        ),
                ],
              );
            }),
          ),
        ),
      ),
    );
  }

  void onLiveCareClinicSelected(GetLiveCareClinicsResponseModel clinic) {
    bookAppointmentsViewModel.setLiveCareSelectedClinic(clinic);
    bookAppointmentsViewModel.setIsDoctorsListLoading(true);
    Navigator.of(context).push(
      CustomPageRoute(
        page: SelectDoctorPage(),
      ),
    );
  }

  void onClinicSelected(GetClinicsListResponseModel clinic) {
    bookAppointmentsViewModel.setSelectedClinic(clinic);
    bookAppointmentsViewModel.setIsDoctorsListLoading(true);
    if (clinic.isLiveCareClinicAndOnline ?? false) {
      Navigator.of(context).push(
        CustomPageRoute(
          page: SelectLivecareClinicPage(onNegativeClicked: (){
              handleDoctorScreen(clinic);
            },),
        ),
      );
    } else {
      handleDoctorScreen(clinic);
    }
  }

  //17 and 235
  void handleDoctorScreen(GetClinicsListResponseModel clinic) async {
    if (widget.isFromRegionFlow) {
      //Dental Clinic Flow
      if (clinic.clinicID == 17) {
        if (appState.isAuthenticated) {
          initDentalAppointmentBookingFlow(int.parse(bookAppointmentsViewModel
                  .currentlySelectedHospitalFromRegionFlow ??
              "0"));
          return;
        } else {
          bookAppointmentsViewModel.setIsChiefComplaintsListLoading(true);
          Navigator.of(context).push(
            CustomPageRoute(
              page: DentalChiefComplaintsPage(),
            ),
          );
          return;
        }
      }
      else if (clinic.clinicID == 253) {
        bookAppointmentsViewModel.resetLaserData();
        bookAppointmentsViewModel.getLaserClinic();
        Navigator.push(
          context,
          CustomPageRoute(
            page: LaserAppointment(),
          ),
        );
        return;
      } else {
        Navigator.push(
          context,
          CustomPageRoute(
            page: SelectDoctorPage(),
          ),
        );
      }
    } else {
      var bottomSheetType = RegionBottomSheetType.FOR_CLINIIC;
      if (clinic.clinicID == 17 || clinic.clinicID == 253) {
        bottomSheetType = RegionBottomSheetType.REGION_FOR_DENTAL_AND_LASER;
      }
      openRegionListBottomSheet(context, bottomSheetType);
    }
  }

  void openRegionListBottomSheet(
      BuildContext context, RegionBottomSheetType type) {
    bookAppointmentsViewModel.setProjectID(null);

    regionalViewModel.flush();
    regionalViewModel.setBottomSheetType(type);
    // AppointmentViaRegionViewmodel? viewmodel = null;
    showCommonBottomSheetWithoutHeight(context, title: "", titleWidget: Consumer<AppointmentViaRegionViewmodel>(builder: (_, data, __) => getTitle(data)), isDismissible: false,
        child: Consumer<AppointmentViaRegionViewmodel>(builder: (_, data, __) {
          return getRegionalSelectionWidget(data);
    }), callBackFunc: () {
    });
  }

  Widget getRegionalSelectionWidget(AppointmentViaRegionViewmodel data) {
    if (data.bottomSheetState == AppointmentViaRegionState.REGION_SELECTION) {
      return RegionBottomSheetBody();
    }
    if (data.bottomSheetState == AppointmentViaRegionState.TYPE_SELECTION) {
      bookAppointmentsViewModel.resetFilterList();
      return FacilityTypeSelectionWidget(
        selectedRegion: data.selectedRegionId ?? "",
      );
    }
    if (data.bottomSheetState == AppointmentViaRegionState.HOSPITAL_SELECTION) {
      return HospitalBottomSheetBody();
    }
    if (data.bottomSheetState == AppointmentViaRegionState.DOCTOR_SELECTION) {
      //if the region screen is opened for the dental clinic then the project id will be in the hospital list as the list is formed form the get project api
      var id = "";
      if (data.regionBottomSheetType == RegionBottomSheetType.REGION_FOR_DENTAL_AND_LASER) {
        id = regionalViewModel.selectedHospital?.hospitalList.first.iD?.toString() ?? "";
      } else {
        id = regionalViewModel.selectedHospital?.patientDoctorAppointmentList?.first.projectID?.toString() ?? "";
      }
      if (bookAppointmentsViewModel.selectedClinic.clinicID == 17) {

        if (appState.isAuthenticated) {
          initDentalAppointmentBookingFlow(int.parse(bookAppointmentsViewModel
              .currentlySelectedHospitalFromRegionFlow ??
              "0"));
        }else {
          bookAppointmentsViewModel.setIsChiefComplaintsListLoading(true);
        }
      }

      if (bookAppointmentsViewModel.selectedClinic.clinicID == 253) {
        {
          bookAppointmentsViewModel.resetLaserData();
          bookAppointmentsViewModel.getLaserClinic();
        }
      }
      bookAppointmentsViewModel.setProjectID(id);
      return SizedBox.shrink();
    }
    else {
      return SizedBox.shrink();
    }
    return SizedBox.shrink();
  }

  getTitle(AppointmentViaRegionViewmodel data) {
    if (data.selectedRegionId == null) {
      return LocaleKeys.selectRegion.tr().toText20(weight: FontWeight.w600);
    } else {
      return Transform.flip(
        flipX: data.isArabic ? true : false,
        child: Utils.buildSvgWithAssets(
          icon: AppAssets.arrow_back,
          iconColor: Color(0xff2B353E),
          fit: BoxFit.contain,
        ),
      ).onPress(() {
        data.handleBackPress();
      });
    }
  }

  void initDentalAppointmentBookingFlow(int projectID) async {
    bookAppointmentsViewModel.setProjectID(projectID.toString());
    LoaderBottomSheet.showLoader(loadingText: "Checking for an existing dental plan, Please wait...".needTranslation);
    await bookAppointmentsViewModel.getPatientDentalEstimation(projectID: projectID).then((value) {
      LoaderBottomSheet.hideLoader();
      if (bookAppointmentsViewModel.patientDentalPlanEstimationList.isNotEmpty) {
        showCommonBottomSheetWithoutHeight(
          // title: LocaleKeys.notice.tr(context: context),
          title: "Dental treatment plan".needTranslation,
          context,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              "You have an existing treatment plan: ".needTranslation.toText14(weight: FontWeight.w500),
              SizedBox(height: 8.h),
              Container(
                width: double.infinity,
                padding: EdgeInsets.all(16.h),
                decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                  color: AppColors.whiteColor,
                  borderRadius: 20.h,
                  hasShadow: true,
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    ListView.separated(
                      shrinkWrap: true,
                      physics: NeverScrollableScrollPhysics(),
                      itemCount: bookAppointmentsViewModel.patientDentalPlanEstimationList.length,
                      separatorBuilder: (_, __) {
                        return Column(
                          children: [
                            SizedBox(height: 8.h),
                            Divider(height: 1, color: AppColors.greyColor),
                            SizedBox(height: 8.h),
                          ],
                        );
                      },
                      itemBuilder: (context, index) {
                        return Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            bookAppointmentsViewModel.patientDentalPlanEstimationList[index].procedureName!.toText12(isBold: true),
                            AppCustomChipWidget(icon: AppAssets.appointment_time_icon, labelText: "${bookAppointmentsViewModel.totalTimeNeededForDentalProcedure} Mins".needTranslation),
                          ],
                        );
                      },
                    ),
                    SizedBox(
                      height: 16.h,
                    ),
                    Divider(height: 1, color: AppColors.greyColor),
                    SizedBox(
                      height: 8.h,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        "Total time required".needTranslation.toText14(isBold: true),
                        AppCustomChipWidget(icon: AppAssets.appointment_time_icon, labelText: "30 Mins".needTranslation),
                      ],
                    )
                  ],
                ),
              ),
              SizedBox(height: 16.h),
              "Would you like to continue it?".needTranslation.toText14(weight: FontWeight.w500),
              SizedBox(height: 16.h),
              Row(
                children: [
                  Expanded(
                    child: CustomButton(
                      text: LocaleKeys.cancel.tr(),
                      onPressed: () {
                        bookAppointmentsViewModel.setIsContinueDentalPlan(false);
                        bookAppointmentsViewModel.setIsChiefComplaintsListLoading(true);
                        Navigator.of(context).pop();
                        Navigator.of(context).push(
                          CustomPageRoute(
                            page: DentalChiefComplaintsPage(),
                          ),
                        );
                      },
                      backgroundColor: AppColors.primaryRedColor,
                      borderColor: AppColors.primaryRedColor,
                      textColor: AppColors.whiteColor,
                      icon: AppAssets.cancel,
                      iconColor: AppColors.whiteColor,
                    ),
                  ),
                  SizedBox(width: 8.h),
                  Expanded(
                    child: CustomButton(
                      text: LocaleKeys.confirm.tr(),
                      onPressed: () async {
                        bookAppointmentsViewModel.setIsContinueDentalPlan(true);
                        Navigator.of(context).pop();
                        Navigator.of(context).push(
                          CustomPageRoute(
                            page: SelectDoctorPage(),
                          ),
                        );
                      },
                      backgroundColor: AppColors.bgGreenColor,
                      borderColor: AppColors.bgGreenColor,
                      textColor: Colors.white,
                      icon: AppAssets.confirm,
                    ),
                  ),
                ],
              )
            ],
          ),
          callBackFunc: () {},
          isFullScreen: false,
          isCloseButtonVisible: true,
        );
      } else {
        Navigator.of(context).push(
          CustomPageRoute(
            page: DentalChiefComplaintsPage(),
          ),
        );
      }
    });
  }
}
