import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/core/api_consts.dart';
import 'package:hmg_patient_app_new/core/app_export.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/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/extensions/widget_extensions.dart';
import 'package:hmg_patient_app_new/features/symptoms_checker/symptoms_checker_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.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/loader/bottomsheet_loader.dart';
import 'package:provider/provider.dart';

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

  @override
  State<UserConsentScreen> createState() => _UserConsentScreenState();
}

class _UserConsentScreenState extends State<UserConsentScreen> {
  bool _isTermsAccepted = false;
  bool _isPrivacyAccepted = false;

  void _onTermsAndConditionsAgreed() {
    setState(() {
      _isTermsAccepted = !_isTermsAccepted;
    });
  }

  void _onPrivacyPolicyAgreed() {
    setState(() {
      _isPrivacyAccepted = !_isPrivacyAccepted;
    });
  }

  bool get _canProceed => _isTermsAccepted && _isPrivacyAccepted;

  void _onNextPressed() async {
    final viewModel = context.read<SymptomsCheckerViewModel>();
    final appState = getIt.get<AppState>();

    LoaderBottomSheet.showLoader(
      loadingText: LocaleKeys.pleaseWait.tr(context: context),
    );

    // For non-authenticated users, fileNo is null
    String? fileNo;
    if (appState.isAuthenticated) {
      final user = appState.getAuthenticatedUser();
      fileNo = user?.patientId.toString();
    }

    await viewModel.getSymptomsUserDetails(
      userName: ApiConsts.symptomsCheckerUsername,
      password: ApiConsts.symptomsCheckerPassword,
      fileNo: fileNo,
      onSuccess: () {
        LoaderBottomSheet.hideLoader();
        context.navigateWithName(AppRoutes.symptomsSelectorPage);
      },
      onError: (String error) {
        LoaderBottomSheet.hideLoader();
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: Column(
        children: [
          Expanded(
            child: CollapsingListView(
              title: LocaleKeys.termsService.tr(),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  LocaleKeys.beforeUsingSymptomsChecker.tr(context: context).toText14(),
                  SizedBox(height: 30.h),
                  LocaleKeys.symptomsCheckerNotDiagnosis.tr(context: context).toText14(),
                  SizedBox(height: 12.h),
                  LocaleKeys.symptomsCheckerNotEmergency.tr(context: context).toText14(),
                  SizedBox(height: 12.h),
                  LocaleKeys.yourDataIsSafe.tr(context: context).toText14(),
                  SizedBox(height: 30.h),
                  GestureDetector(
                    onTap: _onTermsAndConditionsAgreed,
                    child: Container(
                      margin: EdgeInsets.only(bottom: 12.h),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          AnimatedContainer(
                            duration: const Duration(milliseconds: 300),
                            curve: Curves.easeInOut,
                            width: 24.w,
                            height: 24.w,
                            decoration: BoxDecoration(
                              color: _isTermsAccepted ? AppColors.primaryRedColor : Colors.transparent,
                              borderRadius: BorderRadius.circular(5.r),
                              border: Border.all(
                                color: _isTermsAccepted ? AppColors.primaryRedColor : AppColors.checkBoxBorderColor,
                                width: 1.w,
                              ),
                            ),
                            child: _isTermsAccepted ? Icon(Icons.check, size: 16.f, color: AppColors.whiteColor) : null,
                          ),
                          SizedBox(width: 12.w),
                          Expanded(
                            child: RichText(
                              text: TextSpan(
                                text: LocaleKeys.iAgreeAndAcceptTermsAndConditions.tr(context: context),
                                style: TextStyle(
                                  fontSize: 16.f,
                                  fontFamily: getIt.get<AppState>().isArabic() ? 'CairoArabic' : 'Poppins',
                                  fontWeight: FontWeight.w500,
                                  color: AppColors.textColor,
                                ),
                                children: [
                                  WidgetSpan(
                                    child: GestureDetector(
                                      onTap: () {
                                        AppState appState = getIt.get<AppState>();
                                        Utils.openWebView(
                                          url: appState.isArabic() ? AppUrls.hmgTermsUrlAr : AppUrls.hmgTermsUrlEn,
                                        );
                                      },
                                      child: Text(
                                        LocaleKeys.termsAndConditions.tr(context: context),
                                        style: TextStyle(
                                          fontSize: 16.f,
                                          fontFamily: getIt.get<AppState>().isArabic() ? 'CairoArabic' : 'Poppins',
                                          fontWeight: FontWeight.w600,
                                          color: AppColors.primaryRedColor,
                                          decoration: TextDecoration.underline,
                                          decorationColor: AppColors.primaryRedColor,
                                        ),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  SizedBox(
                    height: 16.h,
                  ),
                  GestureDetector(
                    onTap: _onPrivacyPolicyAgreed,
                    child: Container(
                      margin: EdgeInsets.only(bottom: 12.h),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          AnimatedContainer(
                            duration: const Duration(milliseconds: 300),
                            curve: Curves.easeInOut,
                            width: 24.w,
                            height: 24.w,
                            decoration: BoxDecoration(
                              color: _isPrivacyAccepted ? AppColors.primaryRedColor : Colors.transparent,
                              borderRadius: BorderRadius.circular(5.r),
                              border: Border.all(
                                color: _isPrivacyAccepted ? AppColors.primaryRedColor : AppColors.checkBoxBorderColor,
                                width: 1.w,
                              ),
                            ),
                            child: _isPrivacyAccepted ? Icon(Icons.check, size: 16.f, color: AppColors.whiteColor) : null,
                          ),
                          SizedBox(width: 12.w),
                          Expanded(
                            child: RichText(
                              text: TextSpan(
                                text: LocaleKeys.iAgreeHealthInfoCanBeUsed.tr(context: context),
                                style: TextStyle(
                                  fontSize: 16.f,
                                  fontFamily: getIt.get<AppState>().isArabic() ? 'CairoArabic' : 'Poppins',
                                  fontWeight: FontWeight.w500,
                                  color: AppColors.textColor,
                                ),
                                children: [
                                  WidgetSpan(
                                    child: GestureDetector(
                                      onTap: () {
                                        AppState appState = getIt.get<AppState>();
                                        Utils.openWebView(
                                          url: appState.isArabic() ? AppUrls.hmgPrivacyUrlAr : AppUrls.hmgPrivacyUrlEn,
                                        );
                                      },
                                      child: Text(
                                        LocaleKeys.privacyPolicyText.tr(context: context),
                                        style: TextStyle(
                                          fontSize: 16.f,
                                          fontFamily: getIt.get<AppState>().isArabic() ? 'CairoArabic' : 'Poppins',
                                          fontWeight: FontWeight.w600,
                                          color: AppColors.primaryRedColor,
                                          decoration: TextDecoration.underline,
                                          decorationColor: AppColors.primaryRedColor,
                                        ),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ).paddingAll(24.w),
            ),
          ),
          _buildStickyBottomCard(context),
        ],
      ),
    );
  }

  Widget _buildStickyBottomCard(BuildContext context) {
    return Container(
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          SizedBox(height: 16.h),
          Row(
            children: [
              Expanded(
                child: CustomButton(
                  text: LocaleKeys.next.tr(context: context),
                  onPressed: _canProceed ? _onNextPressed : null,
                  isDisabled: !_canProceed,
                  backgroundColor: AppColors.primaryRedColor,
                  borderColor: AppColors.primaryRedColor,
                  textColor: AppColors.whiteColor,
                  fontSize: 16.f,
                ),
              ),
            ],
          ),
          SizedBox(height: 24.h),
        ],
      ).paddingSymmetrical(24.w, 0),
    );
  }
}
