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/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/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/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/comprehensive_checkup/cmc_order_detail_page.dart';
import 'package:hmg_patient_app_new/presentation/comprehensive_checkup/cmc_selection_review_page.dart';
import 'package:hmg_patient_app_new/presentation/comprehensive_checkup/widgets/cmc_ui_selection_helper.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/media_viewer/full_screen_image_viewer.dart';
import 'package:hmg_patient_app_new/widgets/radio_list_tile_widget.dart';
import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart';
import 'package:provider/provider.dart';
import 'package:shimmer/shimmer.dart';

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

  @override
  State<ComprehensiveCheckupPage> createState() => _ComprehensiveCheckupPageState();
}

class _ComprehensiveCheckupPageState extends State<ComprehensiveCheckupPage> {
  int? _selectedServiceId;
  GetCMCServicesResponseModel? _selectedService;

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

    scheduleMicrotask(() async {
      final user = appState.getAuthenticatedUser();
      if (user != null) {
        await hmgServicesViewModel.getAllCmcOrders();
        await hmgServicesViewModel.getAllCmcServices(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) {
    int status = order.statusId ?? 0;
    String statusDisp = order.statusText ?? "";
    Color statusColor;

    if (status == 1) {
      // pending
      statusColor = AppColors.statusPendingColor;
    } else if (status == 2) {
      // processing
      statusColor = AppColors.statusProcessingColor;
    } else if (status == 3) {
      // completed
      statusColor = AppColors.statusCompletedColor;
    } else {
      // cancel / rejected
      statusColor = AppColors.statusRejectedColor;
    }

    final canCancel = order.statusId == 1 || order.statusId == 2;

    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: [
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
                  decoration: BoxDecoration(
                    color: statusColor.withValues(alpha: 0.1),
                    borderRadius: BorderRadius.circular(8.r),
                  ),
                  child: statusDisp.toText12(
                    color: statusColor,
                    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: 16.h),

            // Request ID
            Row(
              children: [
                LocaleKeys.requestID.tr(context: context).toText14(color: AppColors.textColorLight, isBold: true),
                SizedBox(width: 4.w),
                "${order.iD ?? '-'}".toText16(isBold: true),
              ],
            ),

            SizedBox(height: 12.h),

            // Chips for Hospital, Service, and Amount
            Wrap(
              spacing: 6.w,
              runSpacing: 6.h,
              children: [
                // Hospital
                if (order.projectName != null)
                  AppCustomChipWidget(
                    icon: AppAssets.hospital,
                    labelText: order.projectName ?? '-',
                  ),

                // Service
                if (order.serviceText != null)
                  AppCustomChipWidget(
                    icon: AppAssets.file_icon,
                    labelText: order.serviceText ?? '-',
                  ),
              ],
            ),

            SizedBox(height: 16.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: () => CmcUiSelectionHelper.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,
                    ),
                  ),
                ],
              ),
            ]
          ],
        ),
      ),
    );
  }

  Widget _buildServiceSelectionList(List<GetCMCServicesResponseModel> services) {
    if (services.isEmpty) {
      return Center(
        child: Padding(
          padding: EdgeInsets.all(24.h),
          child: Text(
            LocaleKeys.noServicesAvailable.tr(context: context),
            style: TextStyle(
              fontSize: 16.h,
              color: AppColors.greyTextColor,
            ),
          ),
        ),
      );
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(height: 16.h),
        Text(
          LocaleKeys.selectAService.tr(context: context),
          style: TextStyle(
            fontSize: 20.h,
            fontWeight: FontWeight.w700,
            color: AppColors.blackColor,
            letterSpacing: -0.8,
          ),
        ).paddingOnly(left: 16.w, right: 16.w),
        ListView.builder(
          padding: EdgeInsets.zero,
          itemCount: services.length,
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          itemBuilder: (context, index) {
            final service = services[index];
            final appStateLocal = getIt.get<AppState>();
            final serviceName = appStateLocal.isArabic()
                ? (service.textN ?? service.text ?? '')
                : (service.text ?? service.textN ?? '');
            final price = service.priceTotal ?? 0.0;
            return RadioListTileWidget<int>(
              value: service.iD ?? 0,
              groupValue: _selectedServiceId,
              title: serviceName,
              subtitleWidget: Utils.getPaymentAmountWithSymbol(
                isExpanded: false,
                price.toString().toText14(),
                AppColors.blackColor,
                14,
                isSaudiCurrency: true,
              ),
              onChanged: (value) {
                setState(() {
                  _selectedServiceId = value;
                  _selectedService = service;
                });
              },
            );
          },
        ),
        // Illustration image below the services list similar to the old implementation
        SizedBox(height: 12.h),
        Builder(builder: (context) {
          final appStateLocal = getIt.get<AppState>();
          final String imagePath = appStateLocal.isArabic() ? AppAssets.comprehensiveCheckupAr : AppAssets.comprehensiveCheckupEn;
          return Stack(
            children: [
              Utils.buildImgWithAssets(
                icon: imagePath,
                width: double.infinity,
                fit: BoxFit.cover,
              ).paddingAll(16.w),
              Align(
                alignment: Alignment.topRight,
                child: Container(
                  decoration: BoxDecoration(
                    color: Color.fromARGB(51, 0, 0, 0),
                    borderRadius: BorderRadius.circular(1000.r),
                  ),
                  margin: EdgeInsets.all(16.h),
                  child: IconButton(
                    icon: Icon(
                      Icons.zoom_in,
                      color: Colors.white,
                      size: 26.w,
                    ),
                    padding: EdgeInsets.all(10.h),
                    onPressed: () => _showFullScreenImage(context, imagePath, isSvg: false),
                  ),
                ),
              ),
            ],
          );
        }),
      ],
    );
  }

  void _proceedWithSelectedService() {
    if (_selectedService != null) {
      final hmgServicesViewModel = context.read<HmgServicesViewModel>();

      // Store selected service in ViewModel
      hmgServicesViewModel.setSelectedServiceForOrder(_selectedService);
      hmgServicesViewModel.getHospitalsList();
      // Show hospital selection bottom sheet using common helper
      CmcUiSelectionHelper.showHospitalSelectionBottomSheet(
        context: context,
        onHospitalSelected: (hospital) {
          Navigator.of(context).pushReplacement(
            CustomPageRoute(
              page: CmcSelectionReviewPage(selectedService: _selectedService!, preSelectedHospital: hospital),
              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: Colors.white,
              borderRadius: BorderRadius.circular(10.r),
            ),
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return CollapsingListView(
      title: LocaleKeys.comprehensiveCheckup.tr(context: context),
      history: () => Navigator.of(context).push(CustomPageRoute(page: CmcOrderDetailPage(), direction: AxisDirection.up)),
      bottomChild: Consumer<HmgServicesViewModel>(
        builder: (context, hmgServicesViewModel, child) {
          if (hmgServicesViewModel.isCmcOrdersLoading || hmgServicesViewModel.isCmcServicesLoading) return SizedBox.shrink();
          final pendingOrder = _getPendingOrder(hmgServicesViewModel.cmcOrdersList);
          if (pendingOrder == null && _selectedServiceId != null) {
            return SafeArea(
              top: false,
              child: Container(
                decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                  color: AppColors.whiteColor,
                  borderRadius: 24.r,
                  hasShadow: true,
                ),
                padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 12.h, bottom: 16.h),
                child: CustomButton(
                  borderWidth: 0,
                  text: LocaleKeys.next.tr(context: context),
                  onPressed: _proceedWithSelectedService,
                  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.isCmcOrdersLoading || hmgServicesViewModel.isCmcServicesLoading) {
            return _buildLoadingShimmer();
          }
          final pendingOrder = _getPendingOrder(hmgServicesViewModel.cmcOrdersList);
          if (pendingOrder != null) {
            return _buildPendingOrderCard(pendingOrder);
          } else {
            return _buildServiceSelectionList(hmgServicesViewModel.cmcServicesList);
          }
        },
      ),
    );
  }

  void _showFullScreenImage(BuildContext context, String path, {bool isSvg = false}) {
    Navigator.of(context).push(MaterialPageRoute(builder: (_) => FullScreenImageViewer(isSvg: isSvg, path: path)));
  }
}
