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/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/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> {
  late FocusNode _amountFocusNode;

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

  @override
  void initState() {
    super.initState();
    _amountFocusNode = FocusNode();

    // Clear errors when entering recharge wallet page
    WidgetsBinding.instance.addPostFrameCallback((_) {
      habibWalletVM = context.read<HabibWalletViewModel>();
      habibWalletVM.setDepositorDetails(
          appState.getAuthenticatedUser()!.patientId.toString(),
          "${appState.getAuthenticatedUser()!.firstName} ${appState.getAuthenticatedUser()!.lastName}",
          appState.getAuthenticatedUser()!.mobileNumber!);
      habibWalletVM.setSelectedRechargeType(0);
      habibWalletVM.getProjectsList();

      // Clear any previous recharge errors
      habibWalletVM.clearAllRechargeErrors();
    });
  }

  @override
  void dispose() {
    // Clear errors before disposing
    // habibWalletVM.clearAllRechargeErrors();

    _amountFocusNode.dispose();
    amountTextController.dispose();
    notesTextController.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    habibWalletVM = Provider.of<HabibWalletViewModel>(context, listen: false);
    appState = getIt.get<AppState>();
    return PopScope(
      onPopInvokedWithResult: (bool didPop, dynamic result) {
        if (didPop) {
          // Clear errors when user navigates back
          habibWalletVM.clearAllRechargeErrors();
        }
      },
      child: Scaffold(
        backgroundColor: AppColors.bgScaffoldColor,
        body: GestureDetector(
          onTap: () {
            // Dismiss the keyboard and unfocus any focused widget when tapping outside
            _amountFocusNode.unfocus();
            FocusScope.of(context).unfocus();
          },
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                child: CollapsingListView(
                  title: LocaleKeys.rechargePageKey.tr(context: context),
                  child: SingleChildScrollView(
                    child: Padding(
                      padding: EdgeInsets.all(24.h),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Consumer<HabibWalletViewModel>(
                            builder: (context, viewModel, child) {
                              return Container(
                                height: 135.h,
                                decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                                  color: AppColors.whiteColor,
                                  borderRadius: 24.h,
                                  hasShadow: false,
                                  side: BorderSide(
                                    color: viewModel.amountError != null ? AppColors.primaryRedBorderColor : 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
                                      LocaleKeys.amount.tr(context: context).toText14(color: AppColors.greyTextColor, isBold: true),
                                      Spacer(),
                                      Row(
                                        crossAxisAlignment: CrossAxisAlignment.end,
                                        children: [
                                          SizedBox(
                                            width: 150.h,
                                            child: TextInputWidget(
                                              controller: amountTextController,
                                              labelText: "",
                                              hintText: "",
                                              isEnable: true,
                                              prefix: null,
                                              isAllowRadius: true,
                                              isBorderAllowed: false,
                                              isAllowLeadingIcon: true,
                                              autoFocus: true,
                                              fontSize: 25.f,
                                              padding: EdgeInsets.symmetric(horizontal: 8.h, vertical: 0.h),
                                              focusNode: _amountFocusNode,
                                              isWalletAmountInput: true,
                                              keyboardType: TextInputType.numberWithOptions(signed: false, decimal: true),
                                              fontFamily: "Poppins",
                                              onChange: (value) {
                                                // Clear error when user starts typing
                                                viewModel.clearAmountError();
                                              },
                                              // leadingIcon: AppAssets.student_card,
                                            ),
                                          ),
                                          const Spacer(),
                                          ((getIt.get<AppState>().getAuthenticatedUser()!.outSa == 1) ? LocaleKeys.aed.tr(context: context) : LocaleKeys.sar.tr(context: context))
                                              .toText20(color: AppColors.greyTextColor, isBold: true),
                                        ],
                                      ),
                                    ],
                                  ),
                                ),
                              );
                            },
                          ),
                          // Show error message if exists
                          Consumer<HabibWalletViewModel>(
                            builder: (context, viewModel, child) {
                              if (viewModel.amountError != null) {
                                return Padding(
                                  padding: EdgeInsets.only(left: 16.w, top: 8.h),
                                  child: Text(
                                    viewModel.amountError!,
                                    style: TextStyle(
                                      color: AppColors.primaryRedColor,
                                      fontSize: 12.f,
                                    ),
                                  ),
                                );
                              }
                              return SizedBox.shrink();
                            },
                          ),
                          SizedBox(height: 24.h),
                          Consumer<HabibWalletViewModel>(builder: (context, habibWalletVM, child) {
                            return Container(
                              decoration: BoxDecoration(
                                color: AppColors.whiteColor,
                                borderRadius: BorderRadius.circular(24.h),
                                border: Border.all(
                                  color: habibWalletVM.hospitalError != null ? AppColors.primaryRedBorderColor : Colors.transparent,
                                  width: 2.h,
                                ),
                              ),
                              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, applyThemeColor: false),
                                            SizedBox(width: 8.h),
                                            Column(
                                              crossAxisAlignment: CrossAxisAlignment.start,
                                              children: [
                                                (habibWalletVM.getSelectedRechargeTypeValue()).toText12(color: AppColors.greyTextColor, isBold: true),
                                                "${LocaleKeys.medicalFile.tr(context: context)}: ${habibWalletVM.fileNumber}"
                                                    .toText14(color: AppColors.textColor, isBold: true, letterSpacing: -0.2, isEnglishOnly: true),
                                              ],
                                            ),
                                          ],
                                        ),
                                        Utils.buildSvgWithAssets(icon: AppAssets.arrow_down, width: 25.h, height: 25.h),
                                      ],
                                    ).onPress(() async {
                                      habibWalletVM.setCurrentIndex(0);
                                      showCommonBottomSheetWithoutHeight(context, title: LocaleKeys.medicalFile.tr(context: context),
                                          titleWidget: Consumer<HabibWalletViewModel>(builder: (context, habibWalletVM, child) {
                                        return habibWalletVM.currentIndex != 0
                                            ? IconButton(
                                                icon: Transform.flip(
                                                    flipX: appState.isArabic(),
                                                    child: Utils.buildSvgWithAssets(icon: AppAssets.arrow_back, width: 24.h, height: 24.h)),
                                                padding: EdgeInsets.zero,
                                                onPressed: () => habibWalletVM.setCurrentIndex(0),
                                                highlightColor: Colors.transparent,
                                              )
                                            : LocaleKeys.medicalFile.tr(context: context).toText20(isBold: true);
                                      }), 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, applyThemeColor: false),
                                            SizedBox(width: 8.h),
                                            Column(
                                              crossAxisAlignment: CrossAxisAlignment.start,
                                              children: [
                                                LocaleKeys.hospital.tr(context: context).toText12(color: AppColors.greyTextColor, isBold: true),
                                                SizedBox(
                                                  width: MediaQuery.of(context).size.width * 0.55,
                                                  child: (habibWalletVM.selectedHospital != null
                                                          ? habibWalletVM.selectedHospital!.name
                                                          : LocaleKeys.selectHospital.tr(context: context))!
                                                      .toText14(color: AppColors.textColor, isBold: true),
                                                ),
                                              ],
                                            ),
                                          ],
                                        ),
                                        Utils.buildSvgWithAssets(icon: AppAssets.arrow_down, width: 25.h, height: 25.h),
                                      ],
                                    ).onPress(() {
                                      showCommonBottomSheetWithoutHeight(context,
                                          title: LocaleKeys.selectHospital.tr(context: context),
                                          isDismissible: false,
                                          child: SelectHospitalBottomSheet(),
                                          callBackFunc: () {});
                                    }),
                                    // Show hospital error message if exists
                                    if (habibWalletVM.hospitalError != null)
                                      Padding(
                                        padding: EdgeInsets.only(top: 8.h),
                                        child: Text(
                                          habibWalletVM.hospitalError!,
                                          style: TextStyle(
                                            color: AppColors.primaryRedColor,
                                            fontSize: 12.f,
                                          ),
                                        ),
                                      ),
                                    SizedBox(height: 16.h),
                                    Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.1), height: 1.h),
                                    SizedBox(height: 16.h),
                                    Row(
                                      children: [
                                        Utils.buildSvgWithAssets(icon: AppAssets.email_icon, width: 40.h, height: 40.h, applyThemeColor: false),
                                        SizedBox(width: 8.h),
                                        Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            LocaleKeys.email.tr(context: context).toText12(color: AppColors.greyTextColor, isBold: true),
                                            "${appState.getAuthenticatedUser()!.emailAddress}"
                                                .toText14(color: AppColors.textColor, isBold: true, letterSpacing: -0.2, isEnglishOnly: true),
                                          ],
                                        ),
                                      ],
                                    ),
                                    SizedBox(height: 16.h),
                                    Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.1), height: 1.h),
                                    SizedBox(height: 16.h),
                                    TextInputWidget(
                                      labelText: LocaleKeys.notes.tr(context: context),
                                      hintText: "",
                                      controller: notesTextController,
                                      keyboardType: TextInputType.text,
                                      isEnable: true,
                                      prefix: null,
                                      autoFocus: false,
                                      isAllowRadius: true,
                                      isBorderAllowed: false,
                                      isAllowLeadingIcon: true,
                                      leadingIcon: AppAssets.notes_icon,
                                      hasError: false,
                                    ),
                                    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: () {
                    _amountFocusNode.unfocus();
                    FocusScope.of(context).unfocus();

                    // Use ViewModel validation method
                    if (habibWalletVM.validateRechargeForm(amountTextController.text)) {
                      habibWalletVM.setWalletRechargeAmount(num.parse(amountTextController.text.replaceAll(',', '')));
                      habibWalletVM.setNotesText(notesTextController.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: Colors.white,
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  borderRadius: 12,
                  padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                  height: 50.h,
                  icon: AppAssets.appointment_pay_icon,
                  iconColor: Colors.white,
                  iconSize: 18.h,
                ).paddingSymmetrical(24.h, 24.h),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
