import 'dart:async';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.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/book_appointments/models/resp_models/doctors_list_response_model.dart';
import 'package:hmg_patient_app_new/features/my_appointments/my_appointments_view_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/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/loader/bottomsheet_loader.dart';
import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart';
import 'package:provider/provider.dart';

import '../../widgets/chip/app_custom_chip_widget.dart';
import '../../widgets/buttons/custom_button.dart';

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

  @override
  State<MyDoctorsPage> createState() => _MyDoctorsPageState();
}

class _MyDoctorsPageState extends State<MyDoctorsPage> {
  late MyAppointmentsViewModel myAppointmentsViewModel;
  late BookAppointmentsViewModel bookAppointmentsViewModel;
  bool isSortByClinic = true; // default like lab page
  int? expandedIndex;
  final Map<int, GlobalKey> _groupKeys = {};

  @override
  void initState() {
    scheduleMicrotask(() {
      myAppointmentsViewModel.getPatientMyDoctors(isTop8: false);
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    myAppointmentsViewModel = Provider.of<MyAppointmentsViewModel>(context, listen: false);
    bookAppointmentsViewModel = Provider.of<BookAppointmentsViewModel>(context, listen: false);

    return CollapsingListView(
      title: LocaleKeys.myDoctor.tr(context: context),
      child: Consumer<MyAppointmentsViewModel>(builder: (context, myAppointmentsVM, child) {
            // build grouped lists from the flat list
            final clinicMap = <String, List<dynamic>>{};
            final hospitalMap = <String, List<dynamic>>{};

            for (var doc in myAppointmentsVM.patientMyDoctorsList) {
              final clinicKey = (doc.clinicName ?? 'Unknown').trim();
              clinicMap.putIfAbsent(clinicKey, () => []).add(doc);

              final hospitalKey = (doc.projectName ?? doc.projectID?.toString() ?? 'Unknown').toString().trim();
              hospitalMap.putIfAbsent(hospitalKey, () => []).add(doc);
            }

            final patientMyDoctorsByClinic = clinicMap.values.toList();
            final patientMyDoctorsByHospital = hospitalMap.values.toList();
            final patientMyDoctorsViewList = isSortByClinic ? patientMyDoctorsByClinic : patientMyDoctorsByHospital;

            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: 16.h),
                // Add Clinic / Hospital toggle buttons styled like LabOrdersPage
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 24.h),
                  child: Row(
                    children: [
                      CustomButton(
                          text: LocaleKeys.byClinic.tr(context: context),
                          onPressed: () {
                            setState(() {
                              isSortByClinic = true;
                              expandedIndex = null;
                            });
                          },
                          backgroundColor: isSortByClinic ? AppColors.bgRedLightColor : AppColors.whiteColor,
                          borderColor: isSortByClinic ? AppColors.primaryRedColor : AppColors.textColor.withValues(alpha: 0.2),
                          textColor: 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: () {
                             setState(() {
                               isSortByClinic = false;
                               expandedIndex = null;
                             });
                           },
                           backgroundColor: isSortByClinic ? AppColors.whiteColor : AppColors.bgRedLightColor,
                           borderColor: isSortByClinic ? AppColors.textColor.withValues(alpha: 0.2) : AppColors.primaryRedColor,
                           textColor: isSortByClinic ? AppColors.blackColor : AppColors.primaryRedColor,
                           fontSize: 12,
                           isBold: true,
                           borderRadius: 10,
                           padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                           height: 40.h,

                         ),
                     ],
                   ),
                 ),
                SizedBox(height: 16.h),
                ListView.separated(
                  scrollDirection: Axis.vertical,
                  itemCount: myAppointmentsVM.isPatientMyDoctorsLoading ? 5 : (patientMyDoctorsViewList.isNotEmpty ? patientMyDoctorsViewList.length : 0),
                  shrinkWrap: true,
                  physics: NeverScrollableScrollPhysics(),
                  padding: EdgeInsets.only(left: 24.h, right: 24.h),
                  itemBuilder: (context, index) {
                    if (myAppointmentsVM.isPatientMyDoctorsLoading) {
                      return Container(
                        decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                          color: AppColors.whiteColor,
                          borderRadius: 20.h,
                          hasShadow: true,
                        ),
                        child: Padding(
                          padding: EdgeInsets.all(14.h),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Utils.buildImgWithNetwork(
                                    url: "https://hmgwebservices.com/Images/MobileImages/DUBAI/unkown_female.png",
                                    iconColor: AppColors.transparent,
                                    width: 63.h,
                                    height: 63.h,
                                    fit: BoxFit.cover,
                                  ).circle(100).toShimmer2(isShow: true),
                                  SizedBox(width: 16.h),
                                  Expanded(
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        "Dr John Smith".toText16(isBold: true).toShimmer2(isShow: true),
                                        SizedBox(height: 8.h),
                                        Wrap(
                                          direction: Axis.horizontal,
                                          spacing: 3.h,
                                          runSpacing: 4.h,
                                          children: [
                                            AppCustomChipWidget(labelText: "").toShimmer2(isShow: true, width: 16.h),
                                            AppCustomChipWidget(labelText: "").toShimmer2(isShow: true, width: 16.h),
                                          ],
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                      );
                    }

                    final group = patientMyDoctorsViewList[index];
                    final displayName = isSortByClinic ? (group.first.clinicName ?? 'Unknown') : (group.first.projectName ?? 'Unknown');
                    final isExpanded = expandedIndex == index;

                    return AnimatedContainer(
                      duration: const Duration(milliseconds: 300),
                      curve: Curves.easeInOut,
                      margin: EdgeInsets.symmetric(vertical: 8.h),
                      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                        color: AppColors.whiteColor,
                        borderRadius: 20.h,
                        hasShadow: true,
                      ),
                      child: InkWell(
                        onTap: () {
                          setState(() {
                            expandedIndex = isExpanded ? null : index;
                          });
                          WidgetsBinding.instance.addPostFrameCallback((_) {
                            final key = _groupKeys.putIfAbsent(index, () => GlobalKey());
                            if (key.currentContext != null && expandedIndex == index) {
                              Future.delayed(const Duration(milliseconds: 450), () {
                                if (key.currentContext != null) {
                                  Scrollable.ensureVisible(
                                    key.currentContext!,
                                    duration: const Duration(milliseconds: 350),
                                    curve: Curves.easeInOut,
                                    alignment: 0.0,
                                  );
                                }
                              });
                            }
                          });
                        },
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Padding(
                              key: _groupKeys.putIfAbsent(index, () => GlobalKey()),
                              padding: EdgeInsets.all(16.h),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                  AppCustomChipWidget(
                                    labelText: "${group.length} ${LocaleKeys.doctors.tr(context: context)}",
                                  ),
                                  Icon(isExpanded ? Icons.expand_less : Icons.expand_more),
                                    ],
                                  ),
                                  SizedBox(height: 8.h),
                                  Text(
                                    displayName,
                                    style: TextStyle(fontSize: 16.h, fontWeight: FontWeight.w600,),
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ],
                              ),
                            ),
                            AnimatedSwitcher(
                              duration: const Duration(milliseconds: 500),
                              switchInCurve: Curves.easeIn,
                              switchOutCurve: Curves.easeOut,
                              transitionBuilder: (Widget child, Animation<double> animation) {
                                return FadeTransition(
                                  opacity: animation,
                                  child: SizeTransition(
                                    sizeFactor: animation,
                                    axisAlignment: 0.0,
                                    child: child,
                                  ),
                                );
                              },
                              child: isExpanded
                                  ? Container(
                                      key: ValueKey<int>(index),
                                      padding: EdgeInsets.symmetric(horizontal: 16.w),
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          ...group.map<Widget>((doctor) {
                                            return Column(
                                              crossAxisAlignment: CrossAxisAlignment.start,
                                              children: [
                                                Row(
                                                  mainAxisSize: MainAxisSize.min,
                                                  children: [
                                                    Utils.buildImgWithNetwork(
                                                      url: (doctor?.doctorImageURL ?? doctor?.doctorImage ?? "https://hmgwebservices.com/Images/MobileImages/DUBAI/unkown_female.png"),
                                                      iconColor: AppColors.transparent,
                                                      width: 24.w,
                                                      height: 24.h,
                                                      fit: BoxFit.cover,
                                                    ).circle(100),
                                                    SizedBox(width: 8.h),
                                                    Expanded(
                                                      child: (doctor?.doctorName ?? "").toString().toText14(isBold: true),
                                                    ),
                                                  ],
                                                ),
                                                SizedBox(height: 8.h),
                                                Wrap(
                                                  direction: Axis.horizontal,
                                                  spacing: 4.h,
                                                  runSpacing: 4.h,
                                                  children: [
                                                    AppCustomChipWidget(
                                                      labelText: isSortByClinic ? (doctor?.projectName ?? "") : (doctor?.clinicName ?? ""),
                                                    ),
                                                  ],
                                                ),
                                                SizedBox(height: 12.h),
                                                Row(
                                                  children: [
                                                    Expanded(
                                                      flex: 2,
                                                      child: CustomButton(
                                                        icon: AppAssets.view_report_icon,
                                                        iconColor: doctor?.isActiveDoctorProfile == false ? AppColors.inputLabelTextColor.withValues(alpha: 1.0) : AppColors.primaryRedColor,
                                                        iconSize: 16.h,
                                                        text: LocaleKeys.viewProfile.tr(context: context),
                                                        onPressed: doctor?.isActiveDoctorProfile == false ? () {} : () async {
                                                          bookAppointmentsViewModel.setSelectedDoctor(DoctorsListResponseModel(
                                                            clinicID: doctor?.clinicID ?? 0,
                                                            projectID: doctor?.projectID ?? 0,
                                                            doctorID: doctor?.doctorID ?? 0,
                                                            clinicName: doctor?.clinicName,
                                                            projectName: doctor?.projectName,
                                                            // nationalityFlagURL: doctor?.nationalityFlagURL,
                                                            name: doctor?.doctorName,
                                                            doctorImageURL: doctor?.doctorImageURL ?? doctor?.doctorImage,
                                                            speciality: doctor?.doctorSpeciality
                                                          ));
                                                          LoaderBottomSheet.showLoader();
                                                          await bookAppointmentsViewModel.getDoctorProfile(onSuccess: (dynamic respData) {
                                                            LoaderBottomSheet.hideLoader();
                                                            Navigator.of(context).push(
                                                              CustomPageRoute(
                                                                page: DoctorProfilePage(isDoctorAllowedToBook: !doctor?.isLiveCareClinic),
                                                              ),
                                                            );
                                                          }, onError: (err) {
                                                            LoaderBottomSheet.hideLoader();
                                                            showCommonBottomSheetWithoutHeight(
                                                              context,
                                                              child: Utils.getErrorWidget(loadingText: err),
                                                              callBackFunc: () {},
                                                              isFullScreen: false,
                                                              isCloseButtonVisible: true,
                                                            );
                                                          });
                                                        },
                                                        backgroundColor: doctor?.isActiveDoctorProfile == false ? AppColors.inputLabelTextColor.withValues(alpha: 0.3) : AppColors.secondaryLightRedColor,
                                                        borderColor: doctor?.isActiveDoctorProfile == false ? AppColors.inputLabelTextColor.withValues(alpha: 0.01) : AppColors.secondaryLightRedColor,
                                                        textColor: doctor?.isActiveDoctorProfile == false ? AppColors.inputLabelTextColor.withValues(alpha: 1.0) : AppColors.primaryRedColor,
                                                        fontSize: 14,
                                                        isBold: true,
                                                        borderRadius: 12,
                                                        padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
                                                        height: 40.h,
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                                SizedBox(height: 12.h),
                                                Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.05), height: 1.h),
                                                SizedBox(height: 12.h),
                                              ],
                                            );
                                          }).toList(),
                                        ],
                                      ),
                                    )
                                  : const SizedBox.shrink(),
                            ),
                          ],
                        ),
                      ),
                    );
                  },
              separatorBuilder: (BuildContext cxt, int index) => SizedBox(height: 0.h),
            ),
                SizedBox(height: 60.h),
              ],
            );
          }),
    );
  }
}
