import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:hmg_patient_app_new/core/api_consts.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/cache_consts.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/monthly_report/monthly_report_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/services/cache_service.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:provider/provider.dart';

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

  late AppState appState;
  final CacheService _cacheService = GetIt.instance<CacheService>();
  bool isTermsAccepted = true;

  @override
  Widget build(BuildContext context) {
    appState = getIt.get<AppState>();
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: Consumer<MonthlyReportViewModel>(builder: (context, monthlyReportVM, child) {
        return Column(
          children: [
            Expanded(
              child: CollapsingListView(
                title: LocaleKeys.monthlyReports.tr(),
                child: SingleChildScrollView(
                  child: Column(
                    children: [
                      SizedBox(height: 24.h),
                      Container(
                        decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                          color: AppColors.whiteColor,
                          borderRadius: 20.r,
                          hasShadow: false,
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.max,
                          children: [
                            LocaleKeys.patientHealthSummaryReport.tr(context: context).toText14(isBold: true),
                            const Spacer(),
                            Switch(
                              activeTrackColor: AppColors.successColor,
                              value: monthlyReportVM.isHealthSummaryEnabled,
                              onChanged: (newValue) async {
                                monthlyReportVM.setHealthSummaryEnabled(newValue);
                              },
                            ),
                          ],
                        ).paddingSymmetrical(16.h, 16.h),
                      ),
                      SizedBox(height: 16.h),
                      Container(
                        decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                          color: AppColors.whiteColor,
                          borderRadius: 20.r,
                          hasShadow: false,
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            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),
                                    SizedBox(
                                      width: MediaQuery.of(context).size.width * 0.7,
                                      child: "${appState.getAuthenticatedUser()!.emailAddress}"
                                          .toText16(color: AppColors.textColor, isBold: true, maxlines: 2),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ],
                        ).paddingSymmetrical(16.h, 16.h),
                      ),
                      SizedBox(height: 16.h),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Utils.buildSvgWithAssets(icon: AppAssets.prescription_remarks_icon, width: 18.w, height: 18.h),
                          SizedBox(width: 9.h),
                          Expanded(
                            child: LocaleKeys.monthlyHealthSummaryReportDisclaimer
                                .tr(context: context)
                                .toText10(isBold: true, color: AppColors.greyTextColorLight),
                          ),
                        ],
                      ),
                    ],
                  ).paddingSymmetrical(24.w, 0.h),
                ),
              ),
            ),
            Container(
              decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                color: AppColors.whiteColor,
                borderRadius: 24.r,
                hasShadow: true,
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: EdgeInsets.only(top: 32.h, left: 24.w),
                    child: Row(
                      children: [
                        SizedBox(
                          height: 24.0,
                          width: 24.0,
                          child: Checkbox(
                            value: isTermsAccepted,
                            onChanged: (v) {
                              isTermsAccepted = v ?? true;
                            },
                            activeColor: AppColors.primaryRedColor,
                            materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                            visualDensity: VisualDensity.compact,
                          ),
                        ),
                        SizedBox(width: 10.w),
                        "I agree to the ".toText14(isBold: true, letterSpacing: -1.0),
                        "terms and conditions"
                            .toText14(isBold: true, letterSpacing: -1.0, color: AppColors.primaryRedColor, isUnderLine: true)
                            .onPress(() {
                          Utils.openWebView(
                            url: AppUrls.hmgTermsUrlEn,
                          );
                        })
                      ],
                    ),
                  ),
                  CustomButton(
                    text: LocaleKeys.save.tr(),
                    onPressed: () async {
                      LoaderBottomSheet.showLoader(loadingText: LocaleKeys.updatingMonthlyReportStatus.tr(context: context));
                      await monthlyReportVM.updatePatientHealthSummaryReport(
                        rSummaryReport: monthlyReportVM.isHealthSummaryEnabled,
                        onSuccess: (response) async {
                          LoaderBottomSheet.hideLoader();
                          await _cacheService.saveBool(
                            key: CacheConst.isMonthlyReportEnabled,
                            value: monthlyReportVM.isHealthSummaryEnabled,
                          );
                          showCommonBottomSheetWithoutHeight(
                            context,
                            child: Utils.getSuccessWidget(loadingText: LocaleKeys.monthlyReportStatusUpdatedSuccessfully.tr(context: context)),
                            callBackFunc: () {},
                            isFullScreen: false,
                            isCloseButtonVisible: true,
                          );
                        },
                        onError: (error) {
                          // Error is already handled by errorHandlerService in view model
                        },
                      );
                    },
                    backgroundColor: AppColors.primaryRedColor,
                    borderColor: AppColors.primaryRedColor,
                    textColor: AppColors.whiteColor,
                    fontSize: 16.f,
                    fontWeight: FontWeight.w600,
                    borderRadius: 12.r,
                    height: 46.h,
                    iconColor: AppColors.whiteColor,
                    iconSize: 20.h,
                  ).paddingSymmetrical(24.h, 24.h),
                ],
              ),
            ),
          ],
        );
      }),
    );
  }
}
