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/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/my_appointments/models/appointemnet_filters.dart';
import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/patient_appointment_history_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/appointments/widgets/AppointmentFilter.dart';
import 'package:hmg_patient_app_new/presentation/appointments/widgets/appointment_card.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/book_appointment_page.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/chip/app_custom_chip_widget.dart';
import 'package:hmg_patient_app_new/widgets/custom_tab_bar.dart';
import 'package:hmg_patient_app_new/widgets/date_range_selector/date_range_calender.dart';
import 'package:hmg_patient_app_new/widgets/date_range_selector/viewmodel/date_range_view_model.dart';
import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart';
import 'package:provider/provider.dart';

import '../../widgets/common_bottom_sheet.dart' show showCommonBottomSheetWithoutHeight;

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

  @override
  State<MyAppointmentsPage> createState() => _MyAppointmentsPageState();
}

class _MyAppointmentsPageState extends State<MyAppointmentsPage> {
  int? expandedIndex;
  late MyAppointmentsViewModel myAppointmentsViewModel;
  late BookAppointmentsViewModel bookAppointmentsViewModel;

  @override
  void initState() {
    scheduleMicrotask(() {
      if (!myAppointmentsViewModel.isMyAppointmentsLoading) {
        myAppointmentsViewModel.initAppointmentsViewModel();
        myAppointmentsViewModel.getPatientAppointments(true, false, isForTimeLine: false);
      }
      // myAppointmentsViewModel.changeTabToArrived();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    myAppointmentsViewModel = Provider.of<MyAppointmentsViewModel>(context, listen: false);
    bookAppointmentsViewModel = Provider.of<BookAppointmentsViewModel>(context, listen: false);
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: Consumer<MyAppointmentsViewModel>(builder: (context, myAppointmentsVM, child) {
        return CollapsingListView(
          title: LocaleKeys.appointmentsList.tr(context: context),
          child: SingleChildScrollView(
            child: Column(
              children: [
                SizedBox(height: 16.h),
                CustomTabBar(
                  initialIndex: myAppointmentsVM.selectedTabIndex,
                  activeTextColor: Color(0xffED1C2B),
                  activeBackgroundColor: Color(0xffED1C2B).withValues(alpha: .1),
                  tabs: [
                    // CustomTabBarModel(null, LocaleKeys.allAppt.tr(context: context)),
                    CustomTabBarModel(null, LocaleKeys.upcoming.tr(context: context)),
                    CustomTabBarModel(null, LocaleKeys.arrived.tr(context: context)),
                  ],
                  onTabChange: (index) {
                    setState(() {
                      expandedIndex = null;
                    });
                    myAppointmentsViewModel.onTabChange(index);
                    myAppointmentsViewModel.updateListWRTTab(index);
                    context.read<DateRangeSelectorRangeViewModel>().flush();

                    if(index == 1) {
                      myAppointmentsViewModel.loadFullArrivedAppointmentsIfNeeded();
                    }
                  },
                ).paddingSymmetrical(24.h, 0.h),
                // Consumer<MyAppointmentsViewModel>(builder: (context, myAppointmentsVM, child) {
                //   return
                getSelectedTabData(myAppointmentsVM.selectedTabIndex, myAppointmentsVM),
                // }),
              ],
          ),
          ),
        );
      }),
    );
  }

  Widget getSelectedTabData(int index, MyAppointmentsViewModel myAppointmentsVM) {
    return getAppointList(myAppointmentsVM, myAppointmentsVM.filteredAppointmentList);
  }

  Widget getAppointList(MyAppointmentsViewModel myAppointmentsVM, List<PatientAppointmentHistoryResponseModel> filteredAppointmentList) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(height: 16.h),
        // Clinic & Hospital Sort
        Row(
          children: [
            CustomButton(
              text: LocaleKeys.byClinic.tr(context: context),
              onPressed: () {
                myAppointmentsVM.setIsAppointmentsSortByClinic(true);
              },
              backgroundColor: myAppointmentsVM.isAppointmentsSortByClinic ? AppColors.bgRedLightColor : AppColors.whiteColor,
              borderColor: myAppointmentsVM.isAppointmentsSortByClinic ? AppColors.primaryRedColor : AppColors.textColor.withValues(alpha: 0.2),
              textColor: myAppointmentsVM.isAppointmentsSortByClinic ? 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: () {
                myAppointmentsVM.setIsAppointmentsSortByClinic(false);
              },
              backgroundColor: myAppointmentsVM.isAppointmentsSortByClinic ? AppColors.whiteColor : AppColors.bgRedLightColor,
              borderColor: myAppointmentsVM.isAppointmentsSortByClinic ? AppColors.textColor.withValues(alpha: 0.2) : AppColors.primaryRedColor,
              textColor: myAppointmentsVM.isAppointmentsSortByClinic ? AppColors.blackColor : AppColors.primaryRedColor,
              fontSize: 12,
              isBold: true,
              borderRadius: 10,
              padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
              height: 40.h,
            ),
          ],
        ).paddingSymmetrical(24.h, 0.h),
        Visibility(visible: myAppointmentsVM.availableFilters.isNotEmpty, child: getAppointmentFilters(myAppointmentsVM)),
        SizedBox(height: 8.h),
        // Expandable list
        ListView.builder(
          padding: EdgeInsets.only(top: 8.h),
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          itemCount: myAppointmentsVM.isMyAppointmentsLoading
              ? 4
              : filteredAppointmentList.isNotEmpty
                  ? myAppointmentsVM.patientAppointmentsViewList.length
                  : 1,
          itemBuilder: (context, index) {
            final isExpanded = myAppointmentsVM.selectedTabIndex == 0 ? true : expandedIndex == index;
            return myAppointmentsVM.isMyAppointmentsLoading
                ? Container(
                    decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.h, hasShadow: true),
                    child: AppointmentCard(
                      patientAppointmentHistoryResponseModel: PatientAppointmentHistoryResponseModel(),
                      myAppointmentsViewModel: myAppointmentsViewModel,
                      bookAppointmentsViewModel: bookAppointmentsViewModel,
                      isLoading: true,
                      isFromHomePage: false,
                    ),
                  )
                : filteredAppointmentList.isNotEmpty
                    ? 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,
                              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;
                                  });
                                },
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Padding(
                                      padding: EdgeInsets.all(16.h),
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          Row(
                                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                            children: [
                                              AppCustomChipWidget(
                                                  labelText:
                                                  "${myAppointmentsVM.patientAppointmentsViewList[index].patientDoctorAppointmentList!.length} ${LocaleKeys.appointments.tr(context: context)}", isEnglishOnly: true,),
                                              Icon(isExpanded ? Icons.expand_less : Icons.expand_more),
                                            ],
                                          ),
                                          SizedBox(height: 8.h),
                                          myAppointmentsVM.patientAppointmentsViewList[index].filterName!.toText16(isBold: true)
                                        ],
                                      ),
                                    ),
                                    AnimatedSwitcher(
                                      duration: 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: 0.w, vertical: 0.h),
                                              child: Column(
                                                crossAxisAlignment: CrossAxisAlignment.start,
                                                children: [
                                                  ...myAppointmentsVM.patientAppointmentsViewList[index].patientDoctorAppointmentList!.map((appointment) {
                                                    return Column(
                                                      crossAxisAlignment: CrossAxisAlignment.start,
                                                      children: [
                                                        AppointmentCard(
                                                          patientAppointmentHistoryResponseModel: appointment,
                                                          myAppointmentsViewModel: myAppointmentsViewModel,
                                                          bookAppointmentsViewModel: bookAppointmentsViewModel,
                                                          isLoading: false,
                                                          isFromHomePage: false,
                                                        ),
                                                        SizedBox(height: 8.h),
                                                        Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.05), height: 1.h).paddingSymmetrical(16.w, 0.h),
                                                        SizedBox(height: 8.h),
                                                      ],
                                                    );
                                                  }),
                                                ],
                                              ),
                                            )
                                          : SizedBox.shrink(),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ),
                        ),
                      )
                    : Utils.getNoDataWidget(
                        context,
                        noDataText: LocaleKeys.noAppointmentsYet.tr(context: context),
                        callToActionButton: CustomButton(
                          text: LocaleKeys.bookAppo.tr(context: context),
                          onPressed: () {
                            Navigator.of(context).push(
                              CustomPageRoute(
                                page: BookAppointmentPage(),
                              ),
                            );
                          },
                          backgroundColor: Color(0xffFEE9EA),
                          borderColor: Color(0xffFEE9EA),
                          textColor: Color(0xffED1C2B),
                          fontSize: 14.f,
                          isBold: true,
                          borderRadius: 12.r,
                          padding: EdgeInsets.fromLTRB(10.w, 0, 10.w, 0),
                          height: 40.h,
                          icon: AppAssets.add_icon,
                          iconColor: AppColors.primaryRedColor,
                        ).paddingSymmetrical(48.h, 0.h),
                      );
          },
        ).paddingSymmetrical(24.h, 0.h),
        SizedBox(height: 24.h),
      ],
    );
  }

  Widget getAppointmentFilters(MyAppointmentsViewModel myAppointmentsVM) {
    return SizedBox(
        height: 60.h,
        child: Row(
      children: [
        Expanded(
          child: ListView.separated(
              separatorBuilder: (_, index) => SizedBox(
                    width: 8.h,
                  ),
              scrollDirection: Axis.horizontal,
              shrinkWrap: true,
              itemCount: myAppointmentsVM.availableFilters.length,
              itemBuilder: (_, index) => AppointmentFilters(
                    selectedFilter: myAppointmentsVM.selectedFilter,
                    item: myAppointmentsVM.availableFilters[index],
                    onClicked: () {
                      if (myAppointmentsVM.availableFilters[index] == AppointmentListingFilters.DATESELECTION) {
                        showCommonBottomSheetWithoutHeight(
                          title: LocaleKeys.setTheDateRange.tr(context: context),
                          context,
                          child: DateRangeSelector(
                            onRangeSelected: (start, end) {
                              // if (start != null) {
                              myAppointmentsVM.getSelectedDateRange(start, end);
                              // }
                            },
                          ),
                          isFullScreen: false,
                          isCloseButtonVisible: true,
                          callBackFunc: () {},
                        );
                      } else {
                        myAppointmentsVM.setSelectedFilter(myAppointmentsVM.availableFilters[index]);
                        myAppointmentsVM.filterTheListAsPerSelection();
                      }
                    },
                  )),
        ),
      ],
    )).paddingOnly(top: 16.h, left: 24.h, right: 24.h);
  }
}
