import 'dart:async';

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/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/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.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';

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;

  late ScrollController _scrollController;
  final Map<int, GlobalKey> _itemKeys = {};

  @override
  void initState() {
    Clarity.setCurrentScreenName('Select Doctor Page');
    _scrollController = ScrollController();
    scheduleMicrotask(() {
      bookAppointmentsViewModel.setIsNearestAppointmentSelected(false);
      if (bookAppointmentsViewModel.isLiveCareSchedule) {
        bookAppointmentsViewModel.getLiveCareDoctorsList();
      } else {
        if (bookAppointmentsViewModel.selectedClinic.clinicID == 17) {
          bookAppointmentsViewModel.getDentalChiefComplaintDoctorsList();
        } else if (bookAppointmentsViewModel.isGetDocForHealthCal) {
          bookAppointmentsViewModel.getDoctorsListByHealthCal();
        } else {
          bookAppointmentsViewModel.getDoctorsList(isNearest: false);
        }
      }
    });
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    bookAppointmentsViewModel = Provider.of<BookAppointmentsViewModel>(context, listen: false);
    appState = getIt.get<AppState>();
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: CollapsingListView(
        title: LocaleKeys.chooseDoctor.tr(context: context),
        // bottomChild: Container(
        //   decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, customBorder: BorderRadius.only(topLeft: Radius.circular(24.r), topRight: Radius.circular(24.r))),
        //   padding: EdgeInsets.symmetric(vertical: 20.h, horizontal: 20.h),
        //   child: CustomButton(
        //       text: LocaleKeys.search.tr(),
        //       onPressed: () {
        //       },
        //       icon: null,
        //       fontSize: 16.f,
        //       backgroundColor: AppColors.primaryRedColor,
        //       borderColor: AppColors.primaryRedColor,
        //       borderRadius: 12.r,
        //       isBold: true),
        // ),
        child: SingleChildScrollView(
          controller: _scrollController,
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 24.h),
            child: Consumer<BookAppointmentsViewModel>(builder: (context, bookAppointmentsVM, child) {
              return bookAppointmentsViewModel.isLiveCareSchedule
                  ? Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        ListView.separated(
                          padding: EdgeInsets.only(top: 16.h),
                          shrinkWrap: true,
                          physics: NeverScrollableScrollPhysics(),
                          itemCount: bookAppointmentsVM.isDoctorsListLoading ? 5 : (bookAppointmentsVM.liveCareDoctorsList.isNotEmpty ? bookAppointmentsVM.liveCareDoctorsList.length : 1),
                          itemBuilder: (context, index) {
                            // final isExpanded = bookAppointmentsVM.expandedGroupIndex == index;
                            final isExpanded = true;
                            return bookAppointmentsVM.isDoctorsListLoading
                                ? DoctorCard(
                                    doctorsListResponseModel: DoctorsListResponseModel(),
                                    isLoading: true,
                                    bookAppointmentsViewModel: bookAppointmentsViewModel,
                                  )
                                : bookAppointmentsVM.liveCareDoctorsList.isEmpty
                                    ? Utils.getNoDataWidget(context, noDataText: LocaleKeys.noDoctorFound.tr())
                                    : 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: Padding(
                                                padding: EdgeInsets.all(16.h),
                                                child: DoctorCard(
                                                  isLoading: bookAppointmentsVM.isClinicsListLoading,
                                                  doctorsListResponseModel: bookAppointmentsVM.liveCareDoctorsList[index],
                                                  bookAppointmentsViewModel: bookAppointmentsViewModel,
                                                ).onPress(() async {
                                                  bookAppointmentsVM.setSelectedDoctor(bookAppointmentsVM.liveCareDoctorsList[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,
                                                    );
                                                  });
                                                }),
                                              ),
                                            ),
                                          ),
                                        ),
                                      );
                          },
                          separatorBuilder: (BuildContext cxt, int index) => SizedBox(height: 16.h),
                        ),
                        SizedBox(height: 24.h),
                      ],
                    )
                  : 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.filterDoctors("");
                                    textFocusNode.unfocus();
                                  },
                                  child: Utils.buildSvgWithAssets(icon: AppAssets.close_bottom_sheet_icon, width: 20.h, height: 20.h, fit: BoxFit.scaleDown),
                                )
                              : null,
                          onChange: (value) {
                            bookAppointmentsViewModel.filterDoctors(value ?? "");
                          },
                          padding: EdgeInsets.symmetric(
                            vertical: ResponsiveExtension(10).h,
                            horizontal: ResponsiveExtension(15).h,
                          ),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: 16.h),
                  if (bookAppointmentsViewModel.isGetDocForHealthCal && bookAppointmentsVM.showSortFilterButtons)
                    Row(
                      children: [
                        CustomButton(
                          text: LocaleKeys.byClinic.tr(context: context),
                          onPressed: () {
                            bookAppointmentsVM.setIsSortByClinic(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.setIsSortByClinic(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),
                  if (bookAppointmentsViewModel.isGetDocForHealthCal && bookAppointmentsVM.showSortFilterButtons) SizedBox(height: 16.h),
                        // bookAppointmentsVM.doctorsListGrouped.isNotEmpty
                        //     ?
                        Row(
                                mainAxisSize: MainAxisSize.max,
                    children: [
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          LocaleKeys.nearestAppo.tr(context: context).toText13(isBold: true),
                          SizedBox(height: 4.h),
                          LocaleKeys.viewNearestAppos.tr(context: context).toText11(color: AppColors.textColorLight, isBold: true),
                        ],
                      ),
                      const Spacer(),
                      Switch(
                        activeThumbColor: AppColors.successColor,
                        activeTrackColor: AppColors.successColor.withValues(alpha: .15),
                        value: bookAppointmentsVM.isNearestAppointmentSelected,
                        onChanged: (newValue) async {
                          bookAppointmentsVM.setIsNearestAppointmentSelected(newValue);
                                      bookAppointmentsVM.refreshDoctorsList();
                                    },
                                  ),
                                ],
                              ),
                            // : SizedBox.shrink(),
                        ListView.separated(
                    padding: EdgeInsets.only(top: 16.h),
                    shrinkWrap: true,
                    physics: NeverScrollableScrollPhysics(),
                    itemCount: bookAppointmentsVM.isDoctorsListLoading ? 5 : (bookAppointmentsVM.doctorsListGrouped.isNotEmpty ? bookAppointmentsVM.doctorsListGrouped.length : 1),
                    itemBuilder: (context, index) {
                      // final isExpanded = bookAppointmentsVM.expandedGroupIndex == index;
                      final isExpanded = true;
                      return bookAppointmentsVM.isDoctorsListLoading
                          ? DoctorCard(
                              doctorsListResponseModel: DoctorsListResponseModel(),
                              isLoading: true,
                              bookAppointmentsViewModel: bookAppointmentsViewModel,
                            )
                          : bookAppointmentsVM.doctorsListGrouped.isEmpty
                              ? Utils.getNoDataWidget(context, noDataText: LocaleKeys.noDoctorFound.tr())
                              : 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: 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: [
                                                // Header row with count badge and expand/collapse icon
                                                Row(
                                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                                  children: [
                                                    CustomButton(
                                                      text: "${bookAppointmentsVM.doctorsListGrouped[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
                                                      ? (bookAppointmentsVM.doctorsListGrouped[index].first.clinicName ?? 'Unknown')
                                                      : (bookAppointmentsVM.doctorsListGrouped[index].first.projectName ?? 'Unknown'),
                                                  style: TextStyle(fontSize: 16.h, fontWeight: FontWeight.w600,),
                                                  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: bookAppointmentsVM.doctorsListGrouped[index].asMap().entries.map<Widget>((entry) {
                                                              final doctorIndex = entry.key;
                                                              final doctor = entry.value;
                                                              final isLastDoctor = doctorIndex == bookAppointmentsVM.doctorsListGrouped[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(isDoctorAllowedToBook: true,),
                                                                        ),
                                                                      );
                                                                    }, 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(height: 24.h),
                ],
              );
            }),
          ),
        ),
      ),
    );
  }

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