import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/core/app_export.dart';
import 'package:hmg_patient_app_new/core/common_models/generic_api_model.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/extensions/route_extensions.dart';
import 'package:hmg_patient_app_new/extensions/string_extensions.dart';
import 'package:hmg_patient_app_new/features/authentication/authentication_view_model.dart';
import 'package:hmg_patient_app_new/features/habib_wallet/habib_wallet_view_model.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/req_models/create_e_referral_model.dart';
import 'package:hmg_patient_app_new/features/hmg_services/models/ui_models/e_referral_form_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/e_referral/search_e_referral.dart';
import 'package:hmg_patient_app_new/presentation/e_referral/widget/e-referral_otp.dart';
import 'package:hmg_patient_app_new/presentation/e_referral/widget/e_referral_other_details.dart';
import 'package:hmg_patient_app_new/presentation/e_referral/widget/e_referral_patient_info.dart';
import 'package:hmg_patient_app_new/presentation/e_referral/widget/e_referral_requester_form.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/loader/bottomsheet_loader.dart';
import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart';
import 'package:hmg_patient_app_new/widgets/stepper/stepper_widget.dart';
import 'package:provider/provider.dart';

import 'e-referral_validator.dart';
import 'e_referral_form_manager.dart';

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

  @override
  State<NewReferralPage> createState() => _NewReferralPageState();
}

class _NewReferralPageState extends State<NewReferralPage> {
  final PageController _pageController = PageController();
  final ReferralFormManager _formManager = ReferralFormManager(); // Use manager
  int _currentStep = 0;

  double widthOfOneState = ((ResponsiveExtension.screenWidth) / 3) - (20.h);

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadData();
    });
  }

  void _handleNextStep() {
    switch (_currentStep) {
      case 0:
        if (_validateCurrentStep()) {
          OTPService.openOTPScreen(
            context: context,
            formManager: _formManager,
            onSuccess: _proceedToNextStep,
          );
        }
        break;
      case 1:
        if (_validateCurrentStep()) {
          _proceedToNextStep();
        }
        break;
      case 2:
        if (_validateCurrentStep()) {
          _submitReferral();
        }
        break;
    }
  }

  bool _validateCurrentStep() {
    FormValidationErrors stepErrors;

    switch (_currentStep) {
      case 0:
        stepErrors = ReferralValidator.validateStep1(_formManager.formData, context);
        break;
      case 1:
        stepErrors = ReferralValidator.validateStep2(_formManager.formData, context);
        break;
      case 2:
        stepErrors = ReferralValidator.validateStep3(_formManager.formData, context);
        break;
      default:
        stepErrors = FormValidationErrors();
    }

    // Update errors through manager
    _formManager.setErrors(stepErrors);

    return !ReferralValidator.hasErrors(stepErrors);
  }

  void _proceedToNextStep() {
    _pageController.nextPage(
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeInOut,
    );
    setState(() {
      _currentStep++;
    });
  }

  void _submitReferral() {
    CreateEReferralRequestModel createReferralRequestModel = CreateEReferralRequestModel(
        isInsuredPatient: _formManager.formData.isPatientInsured,
        cityCode: _formManager.formData.patientCity!.iD!.toString(),
        cityName: _formManager.formData.patientCity!.description,
        requesterName: _formManager.formData.requesterName,
        requesterContactNo: _formManager.formData.countryEnum.countryCode + _formManager.formData.requesterPhone,
        requesterRelationship: _formManager.formData.relationship?.iD,
        otherRelationship: _formManager.formData.relationship!.iD.toString(),
        fullName: _formManager.formData.patientName,
        identificationNo: int.tryParse(_formManager.formData!.patientIdentification ?? '0'),
        patientMobileNumber: _formManager.formData.patientCountryEnum.countryCode + _formManager.formData.patientPhone,
        preferredBranchCode: _formManager.formData.branch!.iD,
        medicalReportAttachment: _formManager.formData.medicalReportImages,
        insuranceCardAttachment: _formManager.formData.insuredPatientImages,
        preferredBranchName: _formManager.formData.branch!.desciption);

    final hmgServicesVM = context.read<HmgServicesViewModel>();
    LoaderBottomSheet.showLoader();

    hmgServicesVM.createEReferral(
      requestModel: createReferralRequestModel,
      onSuccess: (GenericApiModel response) async{
        LoaderBottomSheet.hideLoader();
        showSuccessBottomSheet(int.parse(response.data), hmgServicesVM);
        await Future.delayed(Duration(milliseconds: 2000)).then((value) {
          if (mounted) Navigator.pop(context);
        });

      },
      onError: (errorMessage) {
        // Handle error (e.g., show error message)
        LoaderBottomSheet.hideLoader();
        showCommonBottomSheetWithoutHeight(context,
            title: LocaleKeys.error.tr(context: context),
            child: Utils.getErrorWidget(
              loadingText: errorMessage.toString(),
            ), callBackFunc: () {
              Navigator.of(context).pop();
            }, isFullScreen: false);
        print(errorMessage);
      },
    );
  }

  void _loadData() {
    final authVM = context.read<AuthenticationViewModel>();
    final habibWalletVM = context.read<HabibWalletViewModel>();
    final hmgServicesVM = context.read<HmgServicesViewModel>();

    hmgServicesVM.getRelationshipType();
    authVM.loadCountriesData();
    hmgServicesVM.getAllCities();
    habibWalletVM.getProjectsList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: AppColors.bgScaffoldColor,
        body: CollapsingListView(
            title: LocaleKeys.eReferral.tr(context: context),
            isClose: false,
            search: () async {
              await Navigator.of(context).push(
                CustomPageRoute(
                  page: SearchEReferralPage(),
                  fullScreenDialog: true,
                  direction: AxisDirection.down,
                ),
              );
            },
            bottomChild: Container(
              color: AppColors.whiteColor,
              padding: EdgeInsets.all(ResponsiveExtension(20).h),
              child: CustomButton(
                text: _currentStep <= 1 ? LocaleKeys.next.tr() : LocaleKeys.submitEReferral.tr(),
                // icon: AppAssets.search_icon,
                iconColor: Colors.white,
                onPressed: () => {_handleNextStep()},
              ),
            ),
            child: ChangeNotifierProvider.value(
              value: _formManager,
              child: SizedBox(
                  height: ResponsiveExtension.screenHeight * 0.65,
                  child: Column(
                    children: [
                      const SizedBox(height: 8),
                      Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: List.generate(3, (index) {
                            // Fill current step and all previous completed steps
                            if (index <= _currentStep) {
                              return StepperWidget(widthOfOneState, AppColors.primaryRedColor, index == _currentStep, 4.h);
                            } else {
                              return StepperWidget(widthOfOneState, AppColors.greyLightColor, false, 4.h);
                            }
                          })),
                      Expanded(
                          child: PageView(
                        controller: _pageController,
                        physics: const NeverScrollableScrollPhysics(),
                        onPageChanged: (index) {
                          setState(() => _currentStep = index);
                        },
                        children: [
                          RequesterFormStep(),
                          PatientInformationStep(),
                          OtherDetailsStep(),
                        ],
                      )),
                    ],
                  )),
            )));
    // );
  }

  showSuccessBottomSheet(int requestId, HmgServicesViewModel hmgServicesViewModel) {
    return showCommonBottomSheetWithoutHeight(
      context,
      child: Padding(
        padding: EdgeInsets.all(16.w),
        child: Column(
          children: [
            Utils.getSuccessWidget(loadingText: LocaleKeys.referralCreatedSuccessfully.tr(context: context)),
            Row(
              children: [
                LocaleKeys.hereIsYourReferralNumber.tr(context: context).toText14(
                      color: AppColors.textColorLight,
                      weight: FontWeight.w600,
                    ),
                SizedBox(width: 4.w),
                ("$requestId").toText16(isBold: true),
              ],
            ),
            SizedBox(height: 24.h),
            Row(
              children: [
                Expanded(
                  child: CustomButton(
                    height: 56.h,
                    text: LocaleKeys.ok.tr(),
                    onPressed: () {
                      context.pop();
                      context.pop();
                      _currentStep = 0;
                    },
                    textColor: AppColors.whiteColor,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
      isCloseButtonVisible: false,
      isDismissible: false,
      isFullScreen: false,
    );
  }
}
