import 'package:clarity_flutter/clarity_flutter.dart';
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/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/doctor_filter/doctor_filter_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/doctor_filter/doctors_filter.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/buttons/custom_button.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';

import '../../features/book_appointments/models/resp_models/doctors_list_response_model.dart';

class SearchDoctorByName extends StatefulWidget {
  const SearchDoctorByName({super.key});

  @override
  State<SearchDoctorByName> createState() => _SearchDoctorByNameState();
}

class _SearchDoctorByNameState extends State<SearchDoctorByName> {
  TextEditingController searchEditingController = TextEditingController();
  FocusNode textFocusNode = FocusNode();
  late BookAppointmentsViewModel bookAppointmentsViewModel;
  late ScrollController _scrollController;
  final Map<int, GlobalKey> _itemKeys = {};

  @override
  void initState() {
    Clarity.setCurrentScreenName('Search By Doctor Name Page');
    _scrollController = ScrollController();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    bookAppointmentsViewModel = Provider.of<BookAppointmentsViewModel>(context, listen: false);
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: Column(
        children: [
          Expanded(
            child: CollapsingListView(
              title: LocaleKeys.chooseDoctor.tr(context: context),
              child: SingleChildScrollView(
                child: Padding(
                  padding: EdgeInsets.symmetric(horizontal: 24.h),
                  child: Column(
                    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,
                              ),
                            ),
                          ),
                          Visibility(
                            visible: context.watch<BookAppointmentsViewModel>().doctorsList.isNotEmpty,
                            child: SizedBox(
                              height: 56.h,
                              width: 56.h,
                              child: DecoratedBox(
                                decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                                  color: AppColors.whiteColor,
                                  borderRadius: 10.h,
                                  hasShadow: false,
                                ),
                                child: Utils.buildSvgWithAssets(
                                  icon: AppAssets.ic_filters,
                                  height: 24.h,
                                  width: 24.h,
                                ).paddingAll(16.h).onPress(() {
                                  context.read<DoctorFilterViewModel>()
                                    ..clearSelection()
                                    ..clearSearchFilters()
                                    ..getFiltersFromDoctorList(bookAppointmentsViewModel.doctorsList)
                                    ..setSelections(bookAppointmentsViewModel.selectedFacilityForFilters?.toList(), bookAppointmentsViewModel.selectedRegionForFilters?.toList(),
                                        bookAppointmentsViewModel.selectedClinicForFilters, bookAppointmentsViewModel.selectedHospitalForFilters, bookAppointmentsViewModel.applyFilters);
                                  Navigator.of(context).push(
                                    PageRouteBuilder(
                                      pageBuilder: (context, animation, secondaryAnimation) => DoctorsFilters(), // Replace YourNewPage with your actual page widget
                                      transitionsBuilder: (context, animation, secondaryAnimation, child) {
                                        const begin = Offset(0.0, 1.0); // Start from the bottom (y=1.0)
                                        const end = Offset.zero; // End at the original position (y=0.0)
                                        final tween = Tween(begin: begin, end: end);
                                        final offsetAnimation = animation.drive(tween);

                                        return SlideTransition(
                                          position: offsetAnimation,
                                          child: child,
                                        );
                                      },
                                      transitionDuration: Duration(milliseconds: 200), // Adjust duration as needed
                                    ),
                                  );
                                }),
                              ),
                            ),
                          )
                        ],
                      ),
                      SizedBox(height: 16.h),
                      Consumer<BookAppointmentsViewModel>(builder: (context, bookAppointmentsVM, child) {
                        return Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            // if (bookAppointmentsVM.isDoctorSearchByNameStarted)
                            //   Row(
                            //     children: [
                            //       CustomButton(
                            //         text: LocaleKeys.byClinic.tr(context: context),
                            //         onPressed: () {
                            //           bookAppointmentsVM.sortFilteredDoctorList(true);
                            //         },
                            //         backgroundColor: bookAppointmentsVM.isSortByClinic ? AppColors.bgRedLightColor : AppColors.whiteColor,
                            //         borderColor: bookAppointmentsVM.isSortByClinic ? AppColors.primaryRedColor : AppColors.textColor.withOpacity(0.2),
                            //         textColor: bookAppointmentsVM.isSortByClinic ? AppColors.primaryRedColor : AppColors.blackColor,
                            //         fontSize: 12,
                            //         isBold: true,
                            //         borderRadius: 10,
                            //         padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                            //         height: 40.h,
                            //       ),
                            //       SizedBox(width: 8.h),
                            //       CustomButton(
                            //         text: LocaleKeys.byHospital.tr(context: context),
                            //         onPressed: () {
                            //           bookAppointmentsVM.sortFilteredDoctorList(false);
                            //         },
                            //         backgroundColor: bookAppointmentsVM.isSortByClinic ? AppColors.whiteColor : AppColors.bgRedLightColor,
                            //         borderColor: bookAppointmentsVM.isSortByClinic ? AppColors.textColor.withOpacity(0.2) : AppColors.primaryRedColor,
                            //         textColor: bookAppointmentsVM.isSortByClinic ? AppColors.blackColor : AppColors.primaryRedColor,
                            //         fontSize: 12,
                            //         isBold: true,
                            //         borderRadius: 10,
                            //         padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                            //         height: 40.h,
                            //       ),
                            //     ],
                            //   ).paddingSymmetrical(0.h, 0.h),
                            bookAppointmentsVM.isDoctorSearchByNameStarted
                                ? ListView.separated(
                                    padding: EdgeInsets.only(top: 20.h),
                                    shrinkWrap: true,
                                    physics: NeverScrollableScrollPhysics(),
                                    itemCount: bookAppointmentsVM.isDoctorsListLoading ? 5 : bookAppointmentsVM.filteredDoctorList.length,
                                    itemBuilder: (context, index) {
                                      // final isExpanded = bookAppointmentsVM.expandedGroupIndex == index;
                                      // final groupedDoctors = bookAppointmentsVM.getGroupedFilteredDoctorsList();

                                      return bookAppointmentsVM.isDoctorsListLoading
                                          ? DoctorCard(
                                              doctorsListResponseModel: DoctorsListResponseModel(),
                                              isLoading: true,
                                              bookAppointmentsViewModel: bookAppointmentsViewModel,
                                            )
                                          : AnimationConfiguration.staggeredList(
                                              position: index,
                                              duration: const Duration(milliseconds: 500),
                                              child: SlideAnimation(
                                                verticalOffset: 100.0,
                                                child: FadeInAnimation(
                                                  child: AnimatedContainer(
                                                    key: _itemKeys.putIfAbsent(index, () => GlobalKey()),
                                                    duration: Duration(milliseconds: 300),
                                                    curve: Curves.easeInOut,
                                                    decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.h, hasShadow: true),
                                                    child: Container(
                                                      key: ValueKey<int>(index),
                                                      padding: EdgeInsets.only(top: 12.h),
                                                      child: DoctorCard(
                                                        doctorsListResponseModel: bookAppointmentsVM.filteredDoctorList[index],
                                                        isLoading: false,
                                                        bookAppointmentsViewModel: bookAppointmentsViewModel,
                                                        isDoctorNameSearch: true,
                                                      ).paddingSymmetrical(16.h, 0.h).onPress(() async {
                                                        bookAppointmentsVM.setSelectedDoctor(bookAppointmentsVM.filteredDoctorList[index]);
                                                        LoaderBottomSheet.showLoader();
                                                        await bookAppointmentsVM.getDoctorProfile(
                                                          onSuccess: (dynamic respData) {
                                                            LoaderBottomSheet.hideLoader();
                                                            Navigator.of(context).push(
                                                              CustomPageRoute(
                                                                page: DoctorProfilePage(isDoctorAllowedToBook: true),
                                                              ),
                                                            );
                                                          },
                                                          onError: (err) {
                                                            LoaderBottomSheet.hideLoader();
                                                            showCommonBottomSheetWithoutHeight(
                                                              context,
                                                              child: Utils.getErrorWidget(loadingText: err),
                                                              callBackFunc: () {},
                                                              isFullScreen: false,
                                                              isCloseButtonVisible: true,
                                                            );
                                                          },
                                                        );
                                                        // Column(
                                                        //   children: bookAppointmentsVM.doctorsList[index].map<Widget>((entry) {
                                                        //     final doctorIndex = entry.key;
                                                        //     final doctor = entry.value;
                                                        //     final isLastDoctor = doctorIndex == groupedDoctors[index].length - 1;
                                                        //     return Column(
                                                        //       children: [
                                                        //         DoctorCard(
                                                        //           doctorsListResponseModel: doctor,
                                                        //           isLoading: false,
                                                        //           bookAppointmentsViewModel: bookAppointmentsViewModel,
                                                        //         ).onPress(() async {
                                                        //           bookAppointmentsVM.setSelectedDoctor(doctor);
                                                        //           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,
                                                        //               );
                                                        //             },
                                                        //           );
                                                        //         }),
                                                        //         if (!isLastDoctor)
                                                        //           Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.05), height: 1.h),
                                                        //       ],
                                                        //     );
                                                        //   }).toList(),
                                                        // ),
                                                      }),
                                                      // InkWell(
                                                      //   onTap: () {
                                                      //     bookAppointmentsVM.toggleGroupExpansion(index);
                                                      //     // After rebuild, ensure the expanded item is visible
                                                      //     WidgetsBinding.instance.addPostFrameCallback((_) {
                                                      //       final key = _itemKeys[index];
                                                      //       if (key != null && key.currentContext != null && bookAppointmentsVM.expandedGroupIndex == index) {
                                                      //         Scrollable.ensureVisible(
                                                      //           key.currentContext!,
                                                      //           duration: Duration(milliseconds: 350),
                                                      //           curve: Curves.easeInOut,
                                                      //           alignment: 0.1,
                                                      //         );
                                                      //       }
                                                      //     });
                                                      //   },
                                                      //   child: Padding(
                                                      //     padding: EdgeInsets.all(16.h),
                                                      //     child: Column(
                                                      //       crossAxisAlignment: CrossAxisAlignment.start,
                                                      //       children: [
                                                      //         Row(
                                                      //           mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                                      //           children: [
                                                      //             CustomButton(
                                                      //                 text: "${groupedDoctors[index].length} ${'doctors'}",
                                                      //                 onPressed: () {},
                                                      //                 backgroundColor: AppColors.greyColor,
                                                      //                 borderColor: AppColors.greyColor,
                                                      //                 textColor: AppColors.blackColor,
                                                      //                 fontSize: 10,
                                                      //                 isBold: true,
                                                      //                 borderRadius: 8,
                                                      //                 padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                                                      //                 height: 30.h),
                                                      //             Icon(isExpanded ? Icons.expand_less : Icons.expand_more),
                                                      //           ],
                                                      //         ),
                                                      //         SizedBox(height: 8.h),
                                                      //         // Clinic/Hospital name as group title
                                                      //         Text(
                                                      //           bookAppointmentsVM.isSortByClinic
                                                      //               ? (groupedDoctors[index].first.clinicName ?? 'Unknown')
                                                      //               : (groupedDoctors[index].first.projectName ?? 'Unknown'),
                                                      //           style: TextStyle(fontSize: 16.h, isBold: true),
                                                      //           overflow: TextOverflow.ellipsis,
                                                      //         ),
                                                      //         // Expanded content - list of doctors in this group
                                                      //         // AnimatedSwitcher(
                                                      //         //   duration: Duration(milliseconds: 400),
                                                      //         //   child: isExpanded
                                                      //         //       ? Container(
                                                      //         //           key: ValueKey<int>(index),
                                                      //         //           padding: EdgeInsets.only(top: 12.h),
                                                      //         //           child: Column(
                                                      //         //             children: groupedDoctors[index].asMap().entries.map<Widget>((entry) {
                                                      //         //               final doctorIndex = entry.key;
                                                      //         //               final doctor = entry.value;
                                                      //         //               final isLastDoctor = doctorIndex == groupedDoctors[index].length - 1;
                                                      //         //               return Column(
                                                      //         //                 children: [
                                                      //         //                   DoctorCard(
                                                      //         //                     doctorsListResponseModel: doctor,
                                                      //         //                     isLoading: false,
                                                      //         //                     bookAppointmentsViewModel: bookAppointmentsViewModel,
                                                      //         //                   ).onPress(() async {
                                                      //         //                     bookAppointmentsVM.setSelectedDoctor(doctor);
                                                      //         //                     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,
                                                      //         //                         );
                                                      //         //                       },
                                                      //         //                     );
                                                      //         //                   }),
                                                      //         //                   if (!isLastDoctor)
                                                      //         //                     Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.05), height: 1.h),
                                                      //         //                 ],
                                                      //         //               );
                                                      //         //             }).toList(),
                                                      //         //           ),
                                                      //         //         )
                                                      //         //       : SizedBox.shrink(),
                                                      //         // ),
                                                      //       ],
                                                      //     ),
                                                      //   ),
                                                      // ),
                                                    ),
                                                  ),
                                                ),
                                              ));
                                    },
                                    separatorBuilder: (BuildContext cxt, int index) => SizedBox(height: 16.h),
                                  )
                                : SizedBox.shrink(),
                            SizedBox(height: 24.h),
                          ],
                        );
                      }),
                    ],
                  ),
                ),
              ),
            ),
          ),
          Container(
            decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
              color: AppColors.whiteColor,
              borderRadius: 24.h,
              hasShadow: true,
            ),
            child: CustomButton(
              text: LocaleKeys.search.tr(context: context),
              onPressed: () async {
                textFocusNode.unfocus();
                print("the value is empty ${searchEditingController.text.isNotEmpty}");
                if (searchEditingController.text.isNotEmpty) {
                  bookAppointmentsViewModel.updateApplyFilters(false);
                  bookAppointmentsViewModel.clearSelection();
                  bookAppointmentsViewModel.updateList();
                  bookAppointmentsViewModel.setIsDoctorSearchByNameStarted(true);
                  bookAppointmentsViewModel.setIsDoctorsListLoading(true);
                  // LoaderBottomSheet.showLoader();
                  await bookAppointmentsViewModel.getDoctorsList(
                      doctorName: searchEditingController.text,
                      onSuccess: (dynamic respData) {},
                      onError: (err) {
                        bookAppointmentsViewModel.setIsDoctorSearchByNameStarted(false);
                        showCommonBottomSheetWithoutHeight(
                          context,
                          child: Utils.getErrorWidget(loadingText: err),
                          callBackFunc: () {},
                          isFullScreen: false,
                          isCloseButtonVisible: true,
                        );
                      });
                } else {
                  showCommonBottomSheetWithoutHeight(
                    context,
                    child: Utils.getErrorWidget(loadingText: "Please enter doctor name to search"),
                    callBackFunc: () {},
                    isFullScreen: false,
                    isCloseButtonVisible: true,
                  );
                }
              },
              backgroundColor: AppColors.primaryRedColor,
              borderColor: AppColors.primaryRedColor,
              textColor: AppColors.whiteColor,
              fontSize: 16.f,
              isBold: true,
              borderRadius: 10.r,
              padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
              height: 50.h,
              icon: AppAssets.search_icon,
              iconColor: AppColors.whiteColor,
              iconSize: 20.h,
            ).paddingSymmetrical(24.h, 24.h),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _scrollController.dispose();
    bookAppointmentsViewModel.doctorsList.clear();
    super.dispose();
  }
}
