import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/cupertino.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/date_util.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/insurance/insurance_view_model.dart';
import 'package:hmg_patient_app_new/features/my_appointments/my_appointments_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/lab/lab_result_item_view.dart';
import 'package:hmg_patient_app_new/services/dialog_service.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/chip/app_custom_chip_widget.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:provider/provider.dart';

class PatientInsuranceCardUpdateCard extends StatelessWidget {
  PatientInsuranceCardUpdateCard({super.key});

  late InsuranceViewModel insuranceViewModel;
  late AppState appState;

  @override
  Widget build(BuildContext context) {
    insuranceViewModel = Provider.of<InsuranceViewModel>(context);
    appState = getIt.get<AppState>();
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            LocaleKeys.insuranceCards.tr(context: context).toText24(isBold: true),
            Utils.buildSvgWithAssets(icon: AppAssets.close_bottom_sheet_icon).onPress(() {
              Navigator.of(context).pop();
            }),
          ],
        ).paddingSymmetrical(24.h, 24.h),
        insuranceViewModel.isInsuranceUpdateDetailsLoading
            ? LabResultItemView(
                onTap: () {},
                labOrder: null,
                index: 0,
                isLoading: true,
              ).paddingSymmetrical(24.h, 24.h)
            : insuranceViewModel.patientInsuranceUpdateResponseModel != null
                ? Container(
                    decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                      color: AppColors.whiteColor,
                      borderRadius: 24,
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        insuranceViewModel.patientInsuranceUpdateResponseModel!.memberName!.toText16(isBold: true),
                        LocaleKeys.policyNumberInsurancePage.tr(namedArgs: {'number': insuranceViewModel.patientInsuranceUpdateResponseModel!.policyNumber.toString()}).toText12(isBold: true, color: AppColors.lightGrayColor, isEnglishOnly: true),
                        SizedBox(height: 8.h),
                        Row(
                          children: [
                            insuranceViewModel.patientInsuranceUpdateResponseModel!.companyName!.toText12(isBold: true),
                            SizedBox(
                              width: 6.h,
                            ),
                            Container(
                              padding: EdgeInsets.symmetric(horizontal: 6.h, vertical: 3.h),
                              decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                                color: AppColors.infoColor,
                                borderRadius: 50,
                              ),
                              child: insuranceViewModel.patientInsuranceUpdateResponseModel!.subCategory!.toText8(isBold: true, color: AppColors.whiteColor),
                            ),
                          ],
                        ),
                        SizedBox(height: 8.h),
                        Wrap(
                          direction: Axis.horizontal,
                          spacing: 4.h,
                          runSpacing: 4.h,
                          children: [
                            AppCustomChipWidget(
                              icon: AppAssets.doctor_calendar_icon,
                              labelText:
                                  "${LocaleKeys.expiryOn.tr(context: context)} ${DateUtil.formatDateToDate(DateTime.parse(insuranceViewModel.patientInsuranceUpdateResponseModel!.effectiveTo!), false)}",
                              isEnglishOnly: true,
                            ),
                            AppCustomChipWidget(
                              labelText: "Member ID: ${insuranceViewModel.patientInsuranceUpdateResponseModel!.memberID!}", isEnglishOnly: true,
                            ),
                          ],
                        ),
                      ],
                    ).paddingSymmetrical(16.h, 16.h),
                  ).paddingSymmetrical(24.h, 0.h)
                : Utils.getNoDataWidget(context, noDataText: LocaleKeys.noInsuranceDataFound.tr(context: context)),
        SizedBox(
          height: 24.h,
        ),
        CustomButton(
          icon: AppAssets.insurance_active_icon,
          iconColor: AppColors.whiteColor,
          iconSize: 20.w,
          text: "${LocaleKeys.updateInsurance.tr(context: context)} ${LocaleKeys.updateInsuranceSubtitle.tr(context: context)}",
          onPressed: () {
            if (insuranceViewModel.patientInsuranceUpdateResponseModel != null) {
              LoaderBottomSheet.showLoader();
              getIt<MyAppointmentsViewModel>().sendPatientUpdateRequest(onSuccess: (val) {
                LoaderBottomSheet.hideLoader();
                insuranceViewModel.setIsInsuranceDataToBeLoaded(true);
                insuranceViewModel.initInsuranceProvider();
                Navigator.pop(context);
              }, onError: (err) {
                insuranceViewModel.updatePatientInsuranceCard(
                    patientID: appState.getAuthenticatedUser()!.patientId!,
                    patientType: appState.getAuthenticatedUser()!.patientType!,
                    patientIdentificationID: appState.getAuthenticatedUser()!.patientIdentificationNo!,
                    mobileNo: appState.getAuthenticatedUser()!.mobileNumber!,
                    insuranceCardImage: "",
                    onSuccess: (val) {
                      LoaderBottomSheet.hideLoader();
                      getIt.get<DialogService>().showCommonBottomSheetWithoutH(
                            message: LocaleKeys.insuranceRequestSubmittedSuccessfully.tr(context: context),
                            label: LocaleKeys.notice.tr(),
                            onOkPressed: () {
                              Navigator.pop(context);
                            },
                            okLabel: "confirm",
                            cancelLabel: LocaleKeys.acknowledged.tr(context: context),
                            isConfirmButton: true,
                          );
                      // showCommonBottomSheetWithoutHeight(
                      //   title: LocaleKeys.success.tr(context: context),
                      //   context,
                      //   child: Utils.getSuccessWidget(loadingText: LocaleKeys.insuranceRequestSubmittedSuccessfully.tr(context: context)),
                      //   callBackFunc: () {
                      //     Navigator.pop(context);
                      //   },
                      //   isFullScreen: false,
                      //   isCloseButtonVisible: false,
                      //   isAutoDismiss: true
                      // );
                      // Future.delayed(Duration(milliseconds: 2000)).then((value) async {
                      //   Navigator.pop(context);
                      // });
                    },
                    onError: (err) {
                      LoaderBottomSheet.hideLoader();
                      showCommonBottomSheetWithoutHeight(
                        title: LocaleKeys.notice.tr(context: context),
                        context,
                        child: Utils.getErrorWidget(loadingText: err.toString()),
                        callBackFunc: () {
                          Navigator.pop(context);
                        },
                        isFullScreen: false,
                        isCloseButtonVisible: true,
                      );
                    });
              });
            }
          },
          backgroundColor: insuranceViewModel.patientInsuranceUpdateResponseModel != null ? AppColors.successColor : AppColors.lightGrayBGColor,
          borderColor: AppColors.successColor.withOpacity(0.01),
          textColor: AppColors.whiteColor,
          fontSize: 16.f,
          isBold: true,
          borderRadius: 12.r,
          padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
        ).paddingSymmetrical(24.w, 0.h),
      ],
    );
  }
}
