import 'dart:async';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.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/authentication/authentication_view_model.dart';
import 'package:hmg_patient_app_new/features/hmg_services/hmg_services_view_model.dart';
import 'package:hmg_patient_app_new/features/hmg_services/models/resq_models/get_cmc_all_orders_resp_model.dart';
import 'package:hmg_patient_app_new/features/hmg_services/models/resq_models/get_cmc_services_resp_model.dart';
import 'package:hmg_patient_app_new/features/location/location_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/home_health_care/hhc_order_detail_page.dart';
import 'package:hmg_patient_app_new/presentation/home_health_care/hhc_selection_review_page.dart';
import 'package:hmg_patient_app_new/presentation/home_health_care/widgets/hhc_ui_selection_helper.dart';
import 'package:hmg_patient_app_new/services/navigation_service.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/map/map_utility_screen.dart';
import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart';
import 'package:provider/provider.dart';
import 'package:shimmer/shimmer.dart';

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

  @override
  State<HhcProceduresPage> createState() => _HhcProceduresPageState();
}

class _HhcProceduresPageState extends State<HhcProceduresPage> {

  late AppState appState;

  @override
  void initState() {
    super.initState();
    final HmgServicesViewModel hmgServicesViewModel = context.read<HmgServicesViewModel>();

    scheduleMicrotask(() async {
      final user = appState.getAuthenticatedUser();
      if (user != null) {
        // Clear previous selections when entering the page
        hmgServicesViewModel.clearHhcServicesSelection();
        await hmgServicesViewModel.getAllHhcOrders();
        await hmgServicesViewModel.getAllHhcServices(patientID: user.patientId ?? 0);
      }
    });
  }

  GetCMCAllOrdersResponseModel? _getPendingOrder(List<GetCMCAllOrdersResponseModel> orders) {
    if (orders.isEmpty) return null;

    // Find pending or processing orders (status 1 or 2)
    for (var order in orders) {
      if (order.statusId == 1 || order.statusId == 2) {
        return order;
      }
    }

    return null;
  }

  Widget _buildPendingOrderCard(GetCMCAllOrdersResponseModel order) {
    final canCancel = order.statusId == 1 || order.statusId == 2;
    final isArabic = getIt.get<AppState>().isArabic();

    List<dynamic> selectedServices = [];
    if (order.orderselectedservice != null) {
      if (order.orderselectedservice is List) {
        selectedServices = order.orderselectedservice as List;
      }
    }

    return Container(
      width: double.infinity,
      margin: EdgeInsets.all(16.w),
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
        color: AppColors.whiteColor,
        borderRadius: 24.h,
        hasShadow: true,
      ),
      child: Padding(
        padding: EdgeInsets.all(16.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Status and Date Row
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    LocaleKeys.requestID.tr(context: context).toText14(color: AppColors.textColorLight, isBold: true),
                    SizedBox(width: 4.w),
                    "${order.iD ?? '-'}".toText16(isBold: true),
                  ],
                ),
                SizedBox(width: 8.w),
                if (order.created != null)
                  DateFormat('MMM dd, yyyy').format(DateTime.parse(order.created!)).toText12(
                        color: AppColors.textColorLight,
                        isBold: true,
                      ),
              ],
            ),
            SizedBox(height: 8.h),

            // Services List
            if (selectedServices.isNotEmpty) ...[
              SizedBox(height: 16.h),
              Container(
                padding: EdgeInsets.all(12.w),
                decoration: BoxDecoration(
                  color: AppColors.bgScaffoldColor,
                  borderRadius: BorderRadius.circular(12.r),
                  border: Border.all(
                    color: AppColors.greyColor.withAlpha(51),
                    width: 1,
                  ),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Icon(
                          Icons.medical_services_outlined,
                          size: 18.h,
                          color: AppColors.primaryRedColor,
                        ),
                        SizedBox(width: 6.w),
                        LocaleKeys.requestedServices.tr().toText14(
                              weight: FontWeight.w600,
                              color: AppColors.blackColor,
                            ),
                      ],
                    ),
                    SizedBox(height: 8.h),
                    ...selectedServices.asMap().entries.map((entry) {
                      int index = entry.key;
                      var service = entry.value;
                      String serviceName = '';

                      if (service is Map) {
                        if (isArabic) {
                          serviceName = service['SelectedServiceNameAR']?.toString() ??
                              service['selectedServiceNameAR']?.toString() ??
                              service['SelectedServiceName']?.toString() ??
                              service['selectedServiceName']?.toString() ??
                              '';
                        } else {
                          serviceName = service['SelectedServiceName']?.toString() ?? service['selectedServiceName']?.toString() ?? '';
                        }
                      }

                      return Padding(
                        padding: EdgeInsets.only(top: index > 0 ? 6.h : 0),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Container(
                              margin: EdgeInsets.only(top: 6.h),
                              width: 6.w,
                              height: 6.w,
                              decoration: BoxDecoration(
                                color: AppColors.primaryRedColor,
                                shape: BoxShape.circle,
                              ),
                            ),
                            SizedBox(width: 8.w),
                            Expanded(
                              child: serviceName.toText14(
                                color: AppColors.blackColor,
                                weight: FontWeight.w600,
                                maxlines: 3,
                              ),
                            ),
                          ],
                        ),
                      );
                    }),
                  ],
                ),
              ),
            ],

            SizedBox(height: 8.h),

            // Info message
            Container(
              padding: EdgeInsets.all(12.w),
              decoration: BoxDecoration(
                color: AppColors.infoBannerBgColor,
                borderRadius: BorderRadius.circular(10.r),
                border: Border.all(
                  color: AppColors.infoBannerBorderColor,
                  width: 1,
                ),
              ),
              child: Row(
                children: [
                  Icon(
                    Icons.info_outline,
                    size: 20.w,
                    color: AppColors.infoBannerIconColor,
                  ),
                  SizedBox(width: 8.w),
                  Expanded(
                    child: LocaleKeys.pendingOrderWait.tr(context: context).toText12(
                          color: AppColors.infoBannerTextColor,
                          isBold: true,
                        ),
                  ),
                ],
              ),
            ),
            if (canCancel) ...[
              SizedBox(height: 16.h),
              Row(
                children: [
                  Expanded(
                    child: CustomButton(
                      text: LocaleKeys.cancelOrder.tr(context: context),
                      onPressed: () => HhcUiSelectionHelper.showCancelConfirmationDialog(context: context, order: order),
                      backgroundColor: AppColors.primaryRedColor,
                      borderColor: AppColors.primaryRedColor,
                      textColor: AppColors.whiteColor,
                      fontSize: 14.f,
                      isBold: true,
                      borderRadius: 10.r,
                      height: 44.h,
                    ),
                  ),
                ],
              ),
            ]
          ],
        ),
      ),
    );
  }

  _buildServicesListBottomsSheet(List<GetCMCServicesResponseModel> services) {
    showCommonBottomSheetWithoutHeight(
      hasBottomPadding: false,
      padding: EdgeInsets.only(top: 24.h),
      context,
      title: LocaleKeys.selectServices.tr(context: context),
      isCloseButtonVisible: true,
      isDismissible: true,
      callBackFunc: () {},
      child: services.isEmpty
          ? Center(
              child: Padding(
                padding: EdgeInsets.all(24.h),
                child: Text(
                  LocaleKeys.noServicesAvailable.tr(context: context),
                  style: TextStyle(
                    fontSize: 16.f,
                    color: AppColors.greyTextColor,
                  ),
                ),
              ),
            )
          : Consumer<HmgServicesViewModel>(
              builder: (context, hmgServicesViewModel, child) {
                final pendingOrder = _getPendingOrder(hmgServicesViewModel.hhcOrdersList);
                final hasSelectedServices = pendingOrder == null && hmgServicesViewModel.selectedHhcServices.isNotEmpty;

                return Stack(
                  children: [
                    // Services List
                    ConstrainedBox(
                      constraints: BoxConstraints(maxHeight: SizeUtils.height * 0.7),
                      child: ListView.separated(
                        separatorBuilder: (context, index) => Divider(color: AppColors.dividerColor).paddingSymmetrical(16.w, 0),
                        padding: EdgeInsets.only(left: 16.w, right: 16.w, bottom: hasSelectedServices ? 160.h : 8.h),
                        shrinkWrap: true,
                        itemCount: services.length,
                        itemBuilder: (context, index) {
                          final service = services[index];
                          final isSelected = hmgServicesViewModel.isHhcServiceSelected(service);
                          final isArabic = getIt.get<AppState>().isArabic();
                          final serviceName = isArabic ? (service.textN ?? service.text ?? '') : (service.text ?? '');

                          return AnimatedContainer(
                            duration: Duration(milliseconds: 300),
                            curve: Curves.easeInOut,
                            child: InkWell(
                              onTap: () => hmgServicesViewModel.toggleHhcServiceSelection(service),
                              borderRadius: BorderRadius.circular(16.r),
                              child: Container(
                                padding: EdgeInsets.all(8.w),
                                child: Row(
                                  children: [
                                    AnimatedContainer(
                                      duration: const Duration(milliseconds: 300),
                                      curve: Curves.easeInOut,
                                      width: 24.w,
                                      height: 24.h,
                                      decoration: BoxDecoration(
                                        color: isSelected ? AppColors.primaryRedColor : Colors.transparent,
                                        borderRadius: BorderRadius.circular(5.r),
                                        border: Border.all(
                                          color: isSelected ? AppColors.primaryRedColor : AppColors.borderGrayColor,
                                          width: 1.w,
                                        ),
                                      ),
                                      child: isSelected ? Icon(Icons.check, size: 18.f, color: AppColors.whiteColor) : null,
                                    ),
                                    SizedBox(width: 12.w),
                                    Expanded(
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          serviceName.toText16(
                                            weight: FontWeight.w600,
                                            color: AppColors.blackColor,
                                            maxlines: 2,
                                          ),
                                        ],
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          );
                        },
                      ),
                    ),

                    if (hasSelectedServices)
                      Positioned(
                        left: 0,
                        right: 0,
                        bottom: 0,
                        child: Container(
                          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 24.h),
                          decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                            color: AppColors.whiteColor,
                            borderRadius: 24.r,
                            hasShadow: true,
                          ),
                          child: Column(
                            children: [
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      LocaleKeys.selectedServices.tr(context: context).toText12(color: AppColors.textColorLight, isBold: true),
                                      Row(
                                        children: [
                                          ("${hmgServicesViewModel.selectedHhcServices.length} ").toText14(isBold: true, weight: FontWeight.bold, isEnglishOnly: true),
                                          LocaleKeys.servicesSelected.tr(context: context).toText14(isBold: true, weight: FontWeight.bold),
                                        ],
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                              SizedBox(height: 16.h),
                              CustomButton(
                                borderWidth: 0,
                                text: LocaleKeys.next.tr(context: context),
                                onPressed: () {
                                  Navigator.pop(context);
                                  _proceedWithSelectedService();
                                },
                                textColor: AppColors.whiteColor,
                                borderRadius: 12.r,
                                borderColor: Colors.transparent,
                              ),
                            ],
                          ),
                        ),
                      ),
                  ],
                );
              },
            ),
    );
  }

  void _proceedWithSelectedService() async {
    final navigationServices = getIt.get<NavigationService>();
    final appState = getIt.get<AppState>();
    final hmgServicesViewModel = context.read<HmgServicesViewModel>();

    if (hmgServicesViewModel.selectedHhcServices.isNotEmpty) {
      context.read<LocationViewModel>().placeValueInController();

      hmgServicesViewModel.setSelectedServiceForHhcOrder(hmgServicesViewModel.selectedHhcServices.first);
      bool result = await navigationServices.push(
        CustomPageRoute(
            page: MapUtilityScreen(
              confirmButtonString: LocaleKeys.submitRequest.tr(context: context),
              titleString: LocaleKeys.selectLocation.tr(context: context),
              subTitleString: LocaleKeys.pleaseSelectTheLocation.tr(context: context),
              isGmsAvailable: appState.isGMSAvailable,
            ),
            direction: AxisDirection.down),
      );

      if (!result) {
        return;
      }

      Navigator.of(context).push(
        CustomPageRoute(
          page: HhcSelectionReviewPage(selectedServices: hmgServicesViewModel.selectedHhcServices),
          direction: AxisDirection.left,
        ),
      );
    }
  }

  Widget _buildLoadingShimmer() {
    return ListView.separated(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      padding: EdgeInsets.all(16.w),
      itemCount: 10,
      separatorBuilder: (_, __) => SizedBox(height: 12.h),
      itemBuilder: (context, index) {
        return Shimmer.fromColors(
          baseColor: Colors.grey[300]!,
          highlightColor: Colors.grey[100]!,
          child: Container(
            height: 80.h,
            decoration: BoxDecoration(
              color: AppColors.whiteColor,
              borderRadius: BorderRadius.circular(10.r),
            ),
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    appState = getIt.get<AppState>();
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: CollapsingListView(
        title: LocaleKeys.homeHealthCare.tr(context: context),
        history: () => appState.isAuthenticated ? Navigator.of(context).push(CustomPageRoute(page: HhcOrderDetailPage(), direction: AxisDirection.up)) : null,
        bottomChild: Consumer(
          builder: (BuildContext context, HmgServicesViewModel hmgServicesViewModel, Widget? child) {
            if (hmgServicesViewModel.isHhcOrdersLoading || hmgServicesViewModel.isHhcServicesLoading) {
              return SizedBox.shrink();
            }
            final pendingOrder = _getPendingOrder(hmgServicesViewModel.hhcOrdersList);
            if (pendingOrder == null) {
              return Container(
                decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                  color: AppColors.whiteColor,
                  borderRadius: 24.r,
                  hasShadow: true,
                ),
                child: Padding(
                  padding: EdgeInsets.all(24.w),
                  child: CustomButton(
                    borderWidth: 0,
                    text: appState.isAuthenticated ? LocaleKeys.createNewRequest.tr(context: context) : LocaleKeys.loginToUseService.tr(context: context),
                    onPressed: () {
                      if(appState.isAuthenticated) {
                        _buildServicesListBottomsSheet(hmgServicesViewModel.hhcServicesList);
                      } else {
                        getIt<AuthenticationViewModel>().onLoginPressed();
                      }
                    },
                    textColor: AppColors.whiteColor,
                    borderRadius: 12.r,
                    borderColor: Colors.transparent,
                    padding: EdgeInsets.symmetric(vertical: 14.h),
                  ),
                ),
              );
            }

            return SizedBox.shrink();
          },
        ),
        child: Consumer<HmgServicesViewModel>(
          builder: (context, hmgServicesViewModel, child) {
            if (hmgServicesViewModel.isHhcOrdersLoading || hmgServicesViewModel.isHhcServicesLoading) {
              return _buildLoadingShimmer();
            }
            final pendingOrder = _getPendingOrder(hmgServicesViewModel.hhcOrdersList);
            if (pendingOrder != null) {
              return _buildPendingOrderCard(pendingOrder);
            } else {
              return Column(
                children: [
                  appState.isAuthenticated ?
                  Center(
                    child: Utils.getNoDataWidget(
                      context,
                      noDataText: LocaleKeys.youHaveNoPendingRequests.tr(context: context),
                    ),
                  ) : LocaleKeys.homeHealthCareText.tr(context: context).toText18(isBold: true).paddingSymmetrical(24.h, 24.h),
                ],
              );
            }
          },
        ),
      ),
    );
  }
}
