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/habib_wallet/habib_wallet_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/habib_wallet/wallet_payment_confirm_page.dart';
import 'package:hmg_patient_app_new/presentation/habib_wallet/widgets/select_hospital_bottom_sheet.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/buttons/custom_button.dart';
import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart';
import 'package:hmg_patient_app_new/widgets/input_widget.dart';
import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart';
import 'package:provider/provider.dart';

import 'widgets/select-medical_file.dart';

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

  @override
  State<RechargeWalletPage> createState() => _RechargeWalletPageState();
}

class _RechargeWalletPageState extends State<RechargeWalletPage> {
  FocusNode textFocusNode = FocusNode();

  late HabibWalletViewModel habibWalletVM;
  late AppState appState;
  final TextEditingController amountTextController = TextEditingController();

  @override
  void initState() {
    scheduleMicrotask(() {
      habibWalletVM.setDepositorDetails(appState.getAuthenticatedUser()!.patientId.toString(), "${appState.getAuthenticatedUser()!.firstName} ${appState.getAuthenticatedUser()!.lastName}",
          appState.getAuthenticatedUser()!.mobileNumber!);
      habibWalletVM.setSelectedRechargeType(0);
      habibWalletVM.getProjectsList();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    habibWalletVM = Provider.of<HabibWalletViewModel>(context, listen: false);
    appState = getIt.get<AppState>();
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            child: CollapsingListView(
              title: LocaleKeys.createAdvancedPayment.tr(context: context),
              child: SingleChildScrollView(
                child: Padding(
                  padding: EdgeInsets.all(24.h),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                        height: 135.h,
                        decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                          color: AppColors.whiteColor,
                          borderRadius: 24.h,
                          hasShadow: false,
                          side: BorderSide(color: AppColors.textColor, width: 2.h),
                        ),
                        child: Padding(
                          padding: EdgeInsets.all(16.h),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              //TODO: Check with hussain to show AED or SAR
                              "Enter an amount".needTranslation.toText14(color: AppColors.greyTextColor, weight: FontWeight.w500),
                              Spacer(),
                              Row(
                                crossAxisAlignment: CrossAxisAlignment.end,
                                children: [
                                  Utils.getPaymentAmountWithSymbol(
                                      SizedBox(
                                        width: 150.h,
                                        child: TextInputWidget(
                                          controller: amountTextController,
                                          labelText: "",
                                          hintText: "",
                                          isEnable: true,
                                          prefix: null,
                                          isAllowRadius: true,
                                          isBorderAllowed: false,
                                          isAllowLeadingIcon: true,
                                          autoFocus: true,
                                          fontSize: 40,
                                          padding: EdgeInsets.symmetric(horizontal: 8.h, vertical: 0.h),
                                          focusNode: textFocusNode,
                                          isWalletAmountInput: true,
                                          keyboardType: TextInputType.numberWithOptions(signed: false, decimal: true),
                                          // leadingIcon: AppAssets.student_card,
                                        ),
                                      ),
                                      AppColors.textColor,
                                      13.h,
                                      isExpanded: false),
                                  const Spacer(),
                                  "SAR".needTranslation.toText20(color: AppColors.greyTextColor, weight: FontWeight.w500),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ),
                      SizedBox(height: 24.h),
                      Consumer<HabibWalletViewModel>(builder: (context, habibWalletVM, child) {
                        return Container(
                          decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                            color: AppColors.whiteColor,
                            borderRadius: 24.h,
                            hasShadow: false,
                          ),
                          child: Padding(
                            padding: EdgeInsets.all(16.h),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [
                                    Row(
                                      children: [
                                        Utils.buildSvgWithAssets(icon: AppAssets.my_account_icon, width: 40.h, height: 40.h),
                                        SizedBox(width: 8.h),
                                        Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            (habibWalletVM.getSelectedRechargeTypeValue()).toText16(color: AppColors.textColor, weight: FontWeight.w500),
                                            "${LocaleKeys.medicalFile.tr(context: context)}: ${habibWalletVM.fileNumber}"
                                                .toText14(color: AppColors.greyTextColor, weight: FontWeight.w500),
                                          ],
                                        ),
                                      ],
                                    ),
                                    Utils.buildSvgWithAssets(icon: AppAssets.arrow_down, width: 25.h, height: 25.h),
                                  ],
                                ).onPress(() async {
                                  habibWalletVM.setCurrentIndex(0);
                                  showCommonBottomSheetWithoutHeight(context, title: "Select Medical File".needTranslation,
                                      titleWidget: Consumer<HabibWalletViewModel>(builder: (context, habibWalletVM, child) {
                                    return habibWalletVM.currentIndex != 0
                                        ? IconButton(
                                            icon: Utils.buildSvgWithAssets(icon: AppAssets.arrow_back, width: 24.h, height: 24.h),
                                            padding: EdgeInsets.zero,
                                            onPressed: () => habibWalletVM.setCurrentIndex(0),
                                            highlightColor: Colors.transparent,
                                          )
                                        : "Select Medical File".needTranslation.toText20(weight: FontWeight.w600);
                                  }), child: Consumer<HabibWalletViewModel>(builder: (context, habibWalletVM, child) {
                                    return MultiPageBottomSheet();
                                  }), callBackFunc: () {}, isFullScreen: false, isCloseButtonVisible: true);
                                }),
                                SizedBox(height: 16.h),
                                Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.1), height: 1.h),
                                SizedBox(height: 16.h),
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [
                                    Row(
                                      children: [
                                        Utils.buildSvgWithAssets(icon: AppAssets.select_hospital_icon, width: 40.h, height: 40.h),
                                        SizedBox(width: 8.h),
                                        Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            LocaleKeys.hospital.tr(context: context).toText16(color: AppColors.textColor, weight: FontWeight.w500),
                                            SizedBox(
                                              width: MediaQuery.of(context).size.width * 0.55,
                                              child: (habibWalletVM.selectedHospital != null ? habibWalletVM.selectedHospital!.name : LocaleKeys.selectHospital.tr(context: context))!
                                                  .toText14(color: AppColors.greyTextColor, weight: FontWeight.w500),
                                            ),
                                          ],
                                        ),
                                      ],
                                    ).onPress(() {
                                      showCommonBottomSheetWithoutHeight(context,
                                          title: LocaleKeys.selectHospital.tr(context: context), isDismissible: false, child: SelectHospitalBottomSheet(), callBackFunc: () {});
                                    }),
                                    Utils.buildSvgWithAssets(icon: AppAssets.arrow_down, width: 25.h, height: 25.h),
                                  ],
                                ),
                                SizedBox(height: 16.h),
                                Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.1), height: 1.h),
                                SizedBox(height: 16.h),
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [
                                    Row(
                                      children: [
                                        Utils.buildSvgWithAssets(icon: AppAssets.email_icon, width: 40.h, height: 40.h),
                                        SizedBox(width: 8.h),
                                        Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            LocaleKeys.email.tr(context: context).toText12(color: AppColors.greyTextColor, fontWeight: FontWeight.w500),
                                            "${appState.getAuthenticatedUser()!.emailAddress}".toText16(color: AppColors.textColor, weight: FontWeight.w500),
                                          ],
                                        ),
                                      ],
                                    ),
                                  ],
                                ),
                                SizedBox(height: 16.h),
                                Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.1), height: 1.h),
                                SizedBox(height: 16.h),
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [
                                    Row(
                                      children: [
                                        Utils.buildSvgWithAssets(icon: AppAssets.notes_icon, width: 40.h, height: 40.h),
                                        SizedBox(width: 8.h),
                                        Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            LocaleKeys.notes.tr(context: context).toText12(color: AppColors.greyTextColor, fontWeight: FontWeight.w500),
                                            "Lorem Ipsum".toText16(color: AppColors.textColor, weight: FontWeight.w500),
                                          ],
                                        ),
                                      ],
                                    ),
                                  ],
                                ),
                                SizedBox(height: 8.h),
                              ],
                            ),
                          ),
                        );
                      }),
                    ],
                  ),
                ),
              ),
            ),
          ),
          //TODO: Handle Family member selection & Other Account Selection
          Container(
            decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
              color: AppColors.whiteColor,
              borderRadius: 24.h,
              hasShadow: false,
            ),
            child: CustomButton(
              text: LocaleKeys.next.tr(context: context),
              onPressed: () {
                if (amountTextController.text.isEmpty) {
                  showCommonBottomSheetWithoutHeight(
                    context,
                    child: Utils.getErrorWidget(loadingText: "Please enter amount to continue.".needTranslation),
                    callBackFunc: () {
                      textFocusNode.requestFocus();
                    },
                    isFullScreen: false,
                    isCloseButtonVisible: true,
                  );
                } else if (habibWalletVM.selectedHospital == null) {
                  showCommonBottomSheetWithoutHeight(
                    context,
                    child: Utils.getErrorWidget(loadingText: "Please select hospital to continue.".needTranslation),
                    callBackFunc: () {
                      textFocusNode.requestFocus();
                    },
                    isFullScreen: false,
                    isCloseButtonVisible: true,
                  );
                } else {
                  habibWalletVM.setWalletRechargeAmount(num.parse(amountTextController.text));
                  // habibWalletVM.setDepositorDetails(appState.getAuthenticatedUser()!.patientId.toString(), "${appState.getAuthenticatedUser()!.firstName} ${appState.getAuthenticatedUser()!.lastName}",
                  //     appState.getAuthenticatedUser()!.mobileNumber!);
                  Navigator.of(context).push(
                    CustomPageRoute(
                      page: WalletPaymentConfirmPage(),
                    ),
                  );
                }
              },
              backgroundColor: AppColors.primaryRedColor,
              borderColor: AppColors.primaryRedColor,
              textColor: AppColors.whiteColor,
              fontSize: 16,
              fontWeight: FontWeight.w500,
              borderRadius: 12,
              padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
              height: 50.h,
              icon: AppAssets.appointment_pay_icon,
              iconColor: AppColors.whiteColor,
              iconSize: 18.h,
            ).paddingSymmetrical(24.h, 24.h),
          ),
        ],
      ),
    );
  }
}
