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/doctors_list_response_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/doctor_profile_page.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/widgets/doctor_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/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:provider/provider.dart';

class SelectDoctorPage extends StatefulWidget {
  SelectDoctorPage({super.key});

  @override
  State<SelectDoctorPage> createState() => _SelectDoctorPageState();
}

class _SelectDoctorPageState extends State<SelectDoctorPage> {
  TextEditingController searchEditingController = TextEditingController();

  FocusNode textFocusNode = FocusNode();

  late AppState appState;
  late BookAppointmentsViewModel bookAppointmentsViewModel;

  @override
  void initState() {
    scheduleMicrotask(() {
      if (bookAppointmentsViewModel.isLiveCareSchedule) {
        bookAppointmentsViewModel.getLiveCareDoctorsList();
      } else {
        if (bookAppointmentsViewModel.selectedClinic.clinicID == 17) {
          bookAppointmentsViewModel.getDentalChiefComplaintDoctorsList();
        } else {
          bookAppointmentsViewModel.getDoctorsList();
        }
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    bookAppointmentsViewModel = Provider.of<BookAppointmentsViewModel>(context, listen: false);
    appState = getIt.get<AppState>();
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: CollapsingListView(
        title: "Choose Doctor".needTranslation,
        child: SingleChildScrollView(
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 24.h),
            child: Consumer<BookAppointmentsViewModel>(builder: (context, bookAppointmentsVM, child) {
              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SizedBox(height: 16.h),
                  Row(
                    spacing: 8.h,
                    children: [
                      Expanded(
                        child: TextInputWidget(
                          labelText: LocaleKeys.search.tr(context: context),
                          hintText: LocaleKeys.doctorName.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,
                          ),
                        ),
                      ),
                    ],
                  ),
                  ListView.separated(
                    padding: EdgeInsets.only(top: 24.h),
                    shrinkWrap: true,
                    physics: NeverScrollableScrollPhysics(),
                    itemCount: bookAppointmentsVM.isDoctorsListLoading
                        ? 5
                        : (bookAppointmentsVM.isLiveCareSchedule
                            ? (bookAppointmentsVM.liveCareDoctorsList.isNotEmpty ? bookAppointmentsVM.liveCareDoctorsList.length : 1)
                            : (bookAppointmentsVM.doctorsList.isNotEmpty ? bookAppointmentsVM.doctorsList.length : 1)),
                    itemBuilder: (context, index) {
                      return bookAppointmentsVM.isDoctorsListLoading
                          ? DoctorCard(
                              doctorsListResponseModel: DoctorsListResponseModel(),
                              isLoading: true,
                              bookAppointmentsViewModel: bookAppointmentsViewModel,
                            )
                          : checkIsDoctorsListEmpty()
                              ? Utils.getNoDataWidget(context, noDataText: "No Doctor found for selected criteria...".needTranslation)
                              : 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: DoctorCard(
                                          doctorsListResponseModel: bookAppointmentsVM.isLiveCareSchedule ? bookAppointmentsVM.liveCareDoctorsList[index] : bookAppointmentsVM.doctorsList[index],
                                          isLoading: false,
                                          bookAppointmentsViewModel: bookAppointmentsViewModel,
                                        ).onPress(() async {
                                          bookAppointmentsVM
                                              .setSelectedDoctor(bookAppointmentsVM.isLiveCareSchedule ? bookAppointmentsVM.liveCareDoctorsList[index] : bookAppointmentsVM.doctorsList[index]);
                                          // bookAppointmentsVM.setSelectedDoctor(DoctorsListResponseModel());
                                          LoaderBottomSheet.showLoader();
                                          await bookAppointmentsVM.getDoctorProfile(onSuccess: (dynamic respData) {
                                            LoaderBottomSheet.hideLoader();
                                            Navigator.of(context).push(
                                              CustomPageRoute(
                                                page: DoctorProfilePage(),
                                              ),
                                            );
                                          }, onError: (err) {
                                            LoaderBottomSheet.hideLoader();
                                            showCommonBottomSheetWithoutHeight(
                                              context,
                                              child: Utils.getErrorWidget(loadingText: err),
                                              callBackFunc: () {},
                                              isFullScreen: false,
                                              isCloseButtonVisible: true,
                                            );
                                          });
                                        }),
                                      ),
                                    ),
                                  ),
                                );
                    },
                    separatorBuilder: (BuildContext cxt, int index) => SizedBox(height: 16.h),
                  ),
                  SizedBox(height: 24.h),
                ],
              );
            }),
          ),
        ),
      ),
    );
  }

  bool checkIsDoctorsListEmpty() {
    if (bookAppointmentsViewModel.isLiveCareSchedule) {
      return bookAppointmentsViewModel.liveCareDoctorsList.isEmpty;
    } else {
      return bookAppointmentsViewModel.doctorsList.isEmpty;
    }
  }
}
