import 'package:easy_localization/easy_localization.dart' show tr, StringTranslateExtension;
import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/core/app_assets.dart';
import 'package:hmg_patient_app_new/core/app_export.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/emergency_services/emergency_services_view_model.dart';
import 'package:hmg_patient_app_new/features/emergency_services/models/resp_model/rrt_procedures_response_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart';
import 'package:provider/provider.dart';

class RrtRequestTypeSelect extends StatelessWidget {
  const RrtRequestTypeSelect({super.key});

  @override
  Widget build(BuildContext context) {
    return Consumer<EmergencyServicesViewModel>(builder: (context, emergencyServicesVM, child) {
      return Column(
      children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              LocaleKeys.rapidResponseTeam.tr(context: context).toText20(color: AppColors.textColor, isBold: true),
              SizedBox(
                height: 16.h,
              ),
              DecoratedBox(
                  decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                    color: AppColors.whiteColor,
                    borderRadius: 20.r,
                  ),
                  child: OptionSelection(context)),
              SizedBox(height: 16.h),
              termsAndCondition(context, emergencyServicesVM),
              SizedBox(height: 16.h),
            ],
          ).paddingSymmetrical(24.w, 0.h),
          bottomPriceContent(context, emergencyServicesVM)
        ],
      );
    });
  }

  bottomPriceContent(BuildContext context, EmergencyServicesViewModel emergencyServicesVM) {
    if (emergencyServicesVM.selectedRRTProcedure == null) return SizedBox.shrink();
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        DecoratedBox(
          decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
              color: AppColors.scaffoldBgColor,
              customBorder: BorderRadius.only(
                topLeft: Radius.circular(24.h),
                topRight: Radius.circular(24.h),
              ),
              hasShadow: true),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            spacing: 12.h,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      spacing: 12.h,
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            LocaleKeys.totalAmountToPay.tr(context: context).toText18(
                                  weight: FontWeight.w600,
                                  color: AppColors.textColor,
                                ),
                            Utils.getPaymentAmountWithSymbol(
                                (Utils.formatNumberToInternationalFormat(context.read<EmergencyServicesViewModel>().selectedRRTProcedure?.patientShare ?? 0))
                                    .toText24(isBold: true, color: AppColors.textColor, letterSpacing: -2),
                                AppColors.blackColor,
                                17.h)
                          ],
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              children: [
                                Utils.buildSvgWithAssets(icon: AppAssets.warning, height: 18.h, width: 18.h),
                                SizedBox(
                                  width: 4.h,
                                ),
                                LocaleKeys.amountPaidAtHospital.tr(context: context).toText11(
                                      color: AppColors.greyTextColor,
                                    ),
                              ],
                            ),
                            Row(
                              children: [
                                LocaleKeys.vat15.tr(context: context).toText12(
                                      isBold: true,
                                      color: AppColors.greyTextColor,
                                    ),
                                "${emergencyServicesVM.selectedRRTProcedure?.patientTaxAmount})".toText14(
                                  weight: FontWeight.w600,
                                      color: AppColors.greyTextColor,
                                    ),
                              ],
                            ),
                          ],
                        )
                      ],
                    ),
                  ),

                  // Utils.getPaymentAmountWithSymbol2(context.read<EmergencyServicesViewModel>().selectedTransportOption?.priceTotal??"0", letterSpacing: -2)
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Utils.getPaymentMethods(),
                  Column(
                    children: [
                      Divider(
                        color: AppColors.dividerColor,
                        thickness: 1.h,
                      ),
                      Utils.getPaymentAmountWithSymbol(
                          (Utils.formatNumberToInternationalFormat(context.read<EmergencyServicesViewModel>().selectedRRTProcedure?.patientShareWithTax ?? 0))
                              .toText24(isBold: true, color: AppColors.textColor, letterSpacing: -2),
                          AppColors.blackColor,
                          17.h),
                    ],
                  )
                ],
              ),
              CustomButton(text: LocaleKeys.next.tr(), onPressed: () {
                Navigator.pop(context);
                emergencyServicesVM.openRRT(context);
                },
                isDisabled: !emergencyServicesVM.agreedToTermsAndCondition,
              )
            ],
          ).paddingAll(24.h),
        ),
      ],
    );
  }

  Widget OptionSelection(BuildContext context) {
    return Selector<EmergencyServicesViewModel, (List<RRTProceduresResponseModel>?, RRTProceduresResponseModel?)>(
      // Select both the list and the currently selected procedure
      selector: (context, viewModel) => (viewModel.RRTProceduresList, viewModel.selectedRRTProcedure),
      builder: (context, data, child) {
        final procedureList = data.$1;
        final selectedProcedure = data.$2;

        // Handle loading or empty state
        if (procedureList == null || procedureList.isEmpty) {
          return const SizedBox.shrink();
        }

        return ListView.separated(
          shrinkWrap: true,
          padding: EdgeInsets.symmetric(vertical: 8.h, horizontal: 16.w),
          // Important for ListView inside a Column
          physics: const NeverScrollableScrollPhysics(),
          // If the parent is scrollable
          itemCount: procedureList.length,
          separatorBuilder: (_, __) => Divider(thickness: 1.h, color: AppColors.dividerColor),
          itemBuilder: (_, index) {
            final procedure = procedureList[index];

            final indexOfSelectedItem = selectedProcedure != null ? procedureList.indexOf(selectedProcedure) : -1;
            return RadioListTile<int>(
              title: (procedure.procedureName ?? "").toText16(color: AppColors.textColor, isBold: true),
              value: index,
              fillColor: WidgetStateProperty.resolveWith((states) {
                if (states.contains(WidgetState.selected)) {
                  return AppColors.primaryRedColor;
                }
                return Color(0xffEEEEEE);
              }),
              contentPadding: EdgeInsets.zero,
              groupValue: indexOfSelectedItem,
              onChanged: (int? newValue) {
                context.read<EmergencyServicesViewModel>().setSelectedRRTProcedure(procedure);
              },
            );
            // return Row(
            //   children: [
            //     Radio<String?>(
            //       // Specify the type for the Radio button
            //       value: procedure.procedureID ?? "",
            //       groupValue: selectedProcedure?.procedureID,
            //       // Compare with the selected procedure's ID
            //       activeColor: AppColors.primaryRedColor,
            //       fillColor: MaterialStateProperty.all(AppColors.primaryRedColor),
            //       onChanged: (value) {
            //         // The onChanged of the Radio button should handle the state update
            //         context.read<EmergencyServicesViewModel>().setSelectedRRTProcedure(procedure);
            //       },
            //     ),
            //     Expanded(
            //       // Use Expanded to allow text to wrap if it's too long
            //       child: (procedure.procedureName ?? "").toText12(color: AppColors.textColor),
            //     )
            //   ],
          },
        );
      },
    );
  }

  termsAndCondition(
    BuildContext context,
    EmergencyServicesViewModel emergencyServicesVM,
  ) {
    return Row(
      children: [
        SizedBox(
          height: 18.h,
          width: 18.w,
          child: Checkbox(
              materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
              value: emergencyServicesVM.agreedToTermsAndCondition,
              checkColor: AppColors.whiteColor,
              fillColor: MaterialStateProperty.resolveWith<Color>((Set<MaterialState> states) {
                if (states.contains(WidgetState.selected)) {
                  return AppColors.errorColor;
                }
                return AppColors.whiteColor;
              }),
              onChanged: (value) {
                emergencyServicesVM.setTermsAndConditions(value ?? false);
              }),
        ),
        Row(
          spacing: 4.w,
          children: [
            SizedBox.shrink(),
            LocaleKeys.agreeTo.tr().toText16(color: AppColors.textColor, isBold: true),
            LocaleKeys.termsConditoins.tr().toText16(color: AppColors.errorColor, isUnderLine: true, isBold: true).onPress(() {
              emergencyServicesVM.getTermsAndConditions();
            }),
          ],
        ),
      ],
    );

    //   CheckboxListTile(
    //   title: Row(
    //     children: [
    //       LocaleKeys.agreeTo.tr().toText12(color: AppColors.textColor),
    //       LocaleKeys.termsConditoins.tr().toText12(color: AppColors.errorColor, isUnderLine: true),
    //     ],
    //   ),
    //   value: emergencyServicesVM.agreedToTermsAndCondition,
    //   onChanged: (value) {
    //     emergencyServicesVM.setTermsAndConditions(value ?? false);
    //   },
    // );
  }
}
