import 'dart:io';

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/widgets/select_hospital_bottom_sheet.dart';
import 'package:hmg_patient_app_new/presentation/refund_request/refund_history_screen.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/image_picker.dart';
import 'package:hmg_patient_app_new/widgets/input_widget.dart';
import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart';
import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart';
import 'package:provider/provider.dart';

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

  @override
  State<WithdrawRequestCreatePage> createState() => _WithdrawRequestCreatePageState();
}

class _WithdrawRequestCreatePageState extends State<WithdrawRequestCreatePage> {
  late HabibWalletViewModel _habibWalletViewModel;
  late AppState _appState;

  final TextEditingController _bankDetailsController = TextEditingController();
  final TextEditingController _descriptionController = TextEditingController();
  final FocusNode _ibanFocusNode = FocusNode();
  final FocusNode _descriptionFocusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    _appState = getIt.get<AppState>();
    _habibWalletViewModel = context.read<HabibWalletViewModel>();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _habibWalletViewModel.getProjectsList();
    });
  }

  @override
  void dispose() {
    _habibWalletViewModel.resetWithdrawForm(silent: true);
    _bankDetailsController.dispose();
    _descriptionController.dispose();
    _ibanFocusNode.dispose();
    _descriptionFocusNode.dispose();
    super.dispose();
  }

  bool get _isFormValid {
    final vm = _habibWalletViewModel;
    return vm.selectedHospital != null &&
        !vm.isAdvancesLoading &&
        _bankDetailsController.text.trim().isNotEmpty &&
        _descriptionController.text.trim().isNotEmpty;
  }

  // ── Bottom bar ────────────────────────────────────────────────────────────

  Widget _buildBottomBar() {
    return Consumer<HabibWalletViewModel>(
      builder: (context, vm, _) {
        final isValid = vm.selectedHospital != null &&
            !vm.isAdvancesLoading &&
            _bankDetailsController.text.trim().isNotEmpty &&
            _descriptionController.text.trim().isNotEmpty;

        return Container(
          decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
            color: AppColors.whiteColor,
            borderRadius: 24.r,
            hasShadow: true,
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              CustomButton(
                text: LocaleKeys.submitRequest.tr(context: context),
                isDisabled: !isValid,
                onPressed: () {
                  final isFormValid = vm.validateWithdrawForm(
                    iban: _bankDetailsController.text,
                    description: _descriptionController.text,
                  );
                  if (isFormValid) {
                    _handleWalletWithdrawalSubmit(vm);
                  }
                },
              ).paddingSymmetrical(24.h, 24.h),
            ],
          ),
        );
      },
    );
  }

  Widget _buildProjectSelectionAndBalance(HabibWalletViewModel habibWalletViewModel) {
    final isArabic = _appState.isArabic();
    return Container(
      padding: EdgeInsets.all(16.h),
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r),
      child: Column(
        children: [
          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),
                    (habibWalletViewModel.selectedHospital != null
                            ? ((isArabic
                                    ? (habibWalletViewModel.selectedHospital!.nameN?.toString() ?? habibWalletViewModel.selectedHospital!.name)
                                    : habibWalletViewModel.selectedHospital!.name) ??
                                LocaleKeys.selectHospital.tr(context: context))
                            : 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(
                onHospitalSelected: (hospital) {
                  habibWalletViewModel.setSelectedHospital(hospital);
                  habibWalletViewModel.fetchAdvancesForHospital();
                },
              ),
              callBackFunc: () {},
            );
          }),
          // Only show divider + amount once hospital is selected
          if (habibWalletViewModel.selectedHospital != null) ...[
            Divider(color: AppColors.bottomNAVBorder, thickness: 1).paddingOnly(top: 16.h),
            habibWalletViewModel.isAdvancesLoading
                ? Container(
                    height: 60.h,
                    // width: 160.w,
                    decoration: BoxDecoration(
                      color: AppColors.whiteColor,
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                  ).toShimmer2(isShow: true, radius: 12.r)
                : Utils.getPaymentAmountWithSymbol(
                    habibWalletViewModel.totalAdvancesBalance.toStringAsFixed(2).toText44(isBold: true),
                    AppColors.blackColor,
                    18.w,
                    isSaudiCurrency: true,
                    isExpanded: false,
                  ),
          ],
        ],
      ),
    );
  }

  Widget _buildBankInputDetails() {
    return Consumer<HabibWalletViewModel>(
      builder: (context, viewModel, _) {
        final hasError = viewModel.ibanError != null || viewModel.withdrawDescriptionError != null;
        return Container(
          padding: EdgeInsets.all(16.h),
          decoration: BoxDecoration(
            color: AppColors.whiteColor,
            borderRadius: BorderRadius.circular(24.r),
            border: Border.all(
              color: hasError ? AppColors.primaryRedBorderColor : Colors.transparent,
              width: 1,
            ),
          ),
          child: Column(
            children: [
              TextInputWidget(
                labelText: LocaleKeys.addIbanDetails.tr(),
                hintText: "SA0000000000000000000000",
                controller: _bankDetailsController,
                focusNode: _ibanFocusNode,
                autoFocus: false,
                keyboardType: TextInputType.text,
                isEnable: true,
                isReadOnly: false,
                prefix: null,
                isBorderAllowed: false,
                isAllowLeadingIcon: true,
                fontSize: 14.f,
                isCountryDropDown: false,
                leadingIcon: AppAssets.bankIcon,
                fontFamily: "Poppins",
                hasError: false,
                errorMessage: viewModel.ibanError,
                onChange: (value) {
                  viewModel.clearIbanError();
                },
                onSubmitted: (value) {
                  _descriptionFocusNode.requestFocus();
                },
              ),
              Divider(color: AppColors.bottomNAVBorder, thickness: 1).withVerticalPadding(16.h),
              TextInputWidget(
                labelText: LocaleKeys.description.tr(),
                hintText: LocaleKeys.enterDescription.tr(),
                controller: _descriptionController,
                focusNode: _descriptionFocusNode,
                autoFocus: false,
                keyboardType: TextInputType.text,
                // leadingIconNeedsContainer: false,
                isEnable: true,
                isReadOnly: false,
                prefix: null,
                isBorderAllowed: false,
                isAllowLeadingIcon: true,
                fontSize: 14.f,
                isCountryDropDown: false,
                leadingIcon: AppAssets.descriptionIcon,
                fontFamily: "Poppins",
                hasError: false,
                errorMessage: viewModel.withdrawDescriptionError,
                onChange: (value) {
                  viewModel.clearWithdrawDescriptionError();
                },
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildImagePickerDropDown() {
    return Container(
      padding: EdgeInsets.all(16.h),
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            children: [
              Utils.buildSvgWithAssets(
                icon: AppAssets.selectImageIcon,
                width: 40.h,
                height: 40.h,
                applyThemeColor: false,
              ),
              SizedBox(width: 8.h),
              Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                LocaleKeys.uploadImage.tr(context: context).toText12(color: AppColors.greyTextColor, isBold: true),
                LocaleKeys.selectImage.tr(context: context).toText14(color: AppColors.textColor, isBold: true),
              ]),
            ],
          ),
          Utils.buildSvgWithAssets(
            icon: AppAssets.arrow_down,
            width: 25.h,
            height: 25.h,
          ),
        ],
      ).onPress(() {
        ImageOptions.showImageOptionsNew(
          context,
          false,
          title: LocaleKeys.selectOptions.tr(context: context),
          (String image, File file) {},
        );
      }),
    );
  }

// ── Submit ────────────────────────────────────────────────────────────────

  void _handleWalletWithdrawalSubmit(HabibWalletViewModel vm) {
    showCommonBottomSheetWithoutHeight(
      context,
      title: LocaleKeys.notice.tr(context: context),
      child: Utils.getWarningWidget(
        loadingText: LocaleKeys.confirmSubmitRequest.tr(context: context),
        isShowActionButtons: true,
        onCancelTap: () {
          Navigator.pop(context);
        },
        onConfirmTap: () async {
          Navigator.pop(context);
          LoaderBottomSheet.showLoader();
          final user = _appState.getAuthenticatedUser();
          final hospital = vm.selectedHospital;
          await vm.submitWalletWithdrawalRequest(
            iban: _bankDetailsController.text.trim(),
            remarks: _descriptionController.text.trim(),
            patientName: '${user?.firstName ?? ''} ${user?.lastName ?? ''}'.trim(),
            patientId: (user?.patientId ?? 0).toString(),
            patientMobileNumber: user?.mobileNumber ?? '',
            patientNationalId: user?.patientIdentificationNo?.toString() ?? '',
            projectId: hospital?.mainProjectID ?? 0,
            projectName: hospital?.name ?? '',
            onSuccess: (response) {
              LoaderBottomSheet.hideLoader();
              _showWithdrawalSuccessBottomSheet(response.refNo ?? '');
            },
            onError: (err) {
              LoaderBottomSheet.hideLoader();
              showCommonBottomSheetWithoutHeight(
                context,
                child: Utils.getErrorWidget(loadingText: err),
                callBackFunc: () {},
              );
            },
          );
        },
      ),
      callBackFunc: () {},
      isFullScreen: false,
      isCloseButtonVisible: true,
    );
  }

  void _showWithdrawalSuccessBottomSheet(String refNo) {
    showCommonBottomSheetWithoutHeight(
      context,
      child: Padding(
        padding: EdgeInsets.all(16.w),
        child: Column(
          children: [
            Utils.getSuccessWidget(loadingText: LocaleKeys.requestSubmittedSuccessfully.tr(context: context)),
            if (refNo.isNotEmpty) ...[
              SizedBox(height: 8.h),
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  LocaleKeys.hereIsYourRequestNumber.tr().toText16(
                        color: AppColors.textColorLight,
                      ),
                  SizedBox(width: 6.w),
                  refNo.toText18(isBold: true, color: AppColors.textColor, isEnglishOnly: true),
                ],
              ).paddingSymmetrical(24.w, 0),
            ],
            SizedBox(height: 24.h),
            Row(
              children: [
                Expanded(
                  child: CustomButton(
                    height: 56.h,
                    text: LocaleKeys.ok.tr(),
                    onPressed: () {
                      Navigator.pop(context); // pop success sheet
                      Navigator.pop(context); // pop refund page
                      Navigator.of(context).push(
                        CustomPageRoute(
                          page: RefundHistoryScreen(
                            refundType: 1, // 2 for wallet, 1 for invoice
                          ),
                        ),
                      );
                    },
                    textColor: AppColors.whiteColor,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
      isCloseButtonVisible: false,
      isDismissible: false,
      isFullScreen: false,
      isAutoDismiss: false,
    );
  }

// ── Build ─────────────────────────────────────────────────────────────────

  @override
  Widget build(BuildContext context) {
    return Consumer<HabibWalletViewModel>(
      builder: (context, habibWalletViewModel, _) {
        return Scaffold(
          backgroundColor: AppColors.bgScaffoldColor,
          body: Column(
            children: [
              Expanded(
                child: CollapsingListView(
                  title: LocaleKeys.requestRefund.tr(context: context),
                  requests: () => Navigator.of(context).push(
                    CustomPageRoute(
                      page: RefundHistoryScreen(
                        refundType: 2, // 2 for wallet, 1 for invoice
                      ),
                    ),
                  ),
                  child: SingleChildScrollView(
                    padding: EdgeInsets.only(bottom: 32.h, left: 24.w, right: 24.w),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        _buildProjectSelectionAndBalance(habibWalletViewModel),
                        if (habibWalletViewModel.selectedHospital != null) ...[
                          SizedBox(height: 16.h),
                          _buildBankInputDetails(),
                          // SizedBox(height: 16.h),
                          // _buildImagePickerDropDown(),
                        ],
                      ],
                    ),
                  ),
                ),
              ),
              _buildBottomBar(),
            ],
          ),
        );
      },
    );
  }
}

// I/flutter (13750): uri: https://uat.hmgwebservices.com/Services/COCWS.svc/REST/SubmitRefund
// [log] body: {"ProjectID":15,"Refund_RefundType":"2","Refund_Project":"مستشفى الريان","Refund_ProjectId":15,"Refund_PatientId":"4770714","PatientMobileNumber":"0504278212","Refund_PatientName":"FAIZ UR REHMAN REHMAN","Refund_NationalId":"2530976584","Refund_DoctorId":0,"Refund_DoctorName":"","Refund_RefundDestination":"2","Refund_IBAN":"SA0380000000608010167519","Refund_Remarks":"teskchjvs","Refund_TotalRefundAmount":1714.75,"Refund_AdvancesList":[{"AdvanceNo":"2026000444","PaidAmount":362.25,"BalanceAmount":362.25,"AdvanceDate":"/Date(1775682000000+0300)/"},{"AdvanceNo":"2026000392","PaidAmount":362.25,"BalanceAmount":362.25,"AdvanceDate":"/Date(1774645200000+0300)/"},{"AdvanceNo":"2026000066","PaidAmount":362.25,"BalanceAmount":362.25,"AdvanceDate":"/Date(1770152400000+0300)/"},{"AdvanceNo":"2026000047","PaidAmount":30.0,"BalanceAmount":30.0,"AdvanceDate":"/Date(1769547600000+0300)/"},{"AdvanceNo":"2025000751","PaidAmount":362.25,"BalanceAmount":362.25,"AdvanceDate":"/Date(1765746000000+0300)/"},{"AdvanceNo":"2025000414","PaidAmount":115.0,"BalanceAmount":115.0,"AdvanceDate":"/Date(1747083600000+0300)/"},{"AdvanceNo":"2025000210","PaidAmount":120.75,"BalanceAmount":120.75,"AdvanceDate":"/Date(1741726800000+0300)/"}],"PatientType":1,"PatientTypeID":1,"TokenID":"@dm!n","PatientID":4770714,"PatientOutSA":0,"SessionID":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlblR5cGUiOjIsIm9iaiI6eyJUaW1lIjoiMjAyNi0wNS0xOFQwNzo1MzoyMS4wMjQ5MDM2WiIsIlBhdGllbnRJRCI6IjQ3NzIxNjMiLCJQYXRpZW50TWVyZ2VkSURzIjoiNDc3MjE2MyIsIlBhdGllbnRPdXRTQSI6ZmFsc2UsIlNoYXJlZElkcyI6IiJ9LCJleHAiOjE3NzkxMzgwMDB9.VHd_kCya33GfK-DywTHwSU1PMewbQB7UhQD1zXS7X5w","VersionID":"21.2","Channel":"3","IPAdress":"10.20.10.20","generalid":"Cs2020@2016$2958","LanguageID":"1","Latitude":"0.0","Longitude":"0.0","DeviceTypeID":"2","IsNewFlutterApp":true}
// [log] response: {"Date":null,"LanguageID":0,"ServiceName":0,"Time":null,"AndroidLink":null,"AuthenticationTokenID":null,"Data":null,"Dataw":false,"DietType":0,"DietTypeID":0,"ErrorCode":null,"ErrorEndUserMessage":"Internal server error occurred.","ErrorEndUserMessageN":null,"ErrorMessage":null,"ErrorStatusCode":0,"ErrorType":0,"FoodCategory":0,"IOSLink":null,"IsAuthenticated":true,"MealOrderStatus":0,"MealType":0,"MessageStatus":2,"NumberOfResultRecords":0,"PatientBlodType":null,"RequestId":null,"SuccessMsg":null,"SuccessMsgN":null,"VidaUpdatedResponse":null,"ENSAT_GetPatientRequestListResponse":null,"ENSAT_Patient_External_Response":null,"ETQAN_CreateIncident_Response":null,"ETQAN_GetEmployeeOVRRequests_Response":null,"ETQAN_GetIncidentRequest_Response":null,"ETQAN_GetProjects_Response":null,"ITGRequest":null,"Itg_FormAttachmentsList":null,"ListCOCItems":null,"Message":"Refunds API returned status 500. Body: {\"message\":\"Internal server error occurred.\"}","Mohemm_ENSAT_GetItgToken_Response":null,"Mohemm_ITG_DepartmentSectionsList":null,"Mohemm_ITG_Pending_Task_ResponseItem":null,"Mohemm_ITG_ProjectDepartmentsList":null,"Mohemm_ITG_ResponseItem":null,"Mohemm_ITG_SectionTopicsList":null,"Mohemm_ITG_TicketDetailsList":null,"Mohemm_ITG_TicketTransactionsList":null,"Mohemm_ITG_TicketsByEmployeeList":null,"Mohemm_Itg_ProjectsList":null,"Mohemm_Itg_TicketTypesList":null,"ReferenceNumber":null,"Refund_InvoicesList":null,"Refund_PatientIdDisplay":null,"Refund_RefNo":null,"Refund_RefundTypeDisplay":null,"Refund_StatusItem":null,"Refund_TotalInvoices":0,"Refund_VerifyResult":null,"RequestType":null,"TotalCount":0,"statuseCode":500}
