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_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/date_util.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/hmg_services/hmg_services_view_model.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:provider/provider.dart';

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

  @override
  State<UserInfoSelectionScreen> createState() => _UserInfoSelectionScreenState();
}

class _UserInfoSelectionScreenState extends State<UserInfoSelectionScreen> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _initializeUserInfo();
    });
  }

  /// Initialize user info from appState if user is logged in
  void _initializeUserInfo() {
    final appState = getIt.get<AppState>();
    final viewModel = context.read<SymptomsCheckerViewModel>();

    if (appState.isAuthenticated) {
      final user = appState.getAuthenticatedUser();
      getIt.get<HmgServicesViewModel>().getPatientVitalSign();

      if (user == null) return;

      // Populate gender (gender is int: 1=Male, 2=Female)
      // Use internal keys (male/female) for storage
      if (user.gender != null) {
        String genderKey = user.gender == 1
            ? "male"
            : user.gender == 2
                ? "female"
                : "other";
        viewModel.setGender(genderKey);
      }

      if (user.dateofBirth != null && user.dateofBirth!.isNotEmpty) {
        try {
          DateTime dob = DateTime.parse(user.dateofBirth!);
          viewModel.setDateOfBirth(dob);
        } catch (e) {
          // If date parsing fails, ignore and let user fill manually
        }
      }

      // Note: AuthenticatedUser doesn't have height/weight fields
      // User will need to fill these manually
    }
    // If not authenticated or fields are empty, user will fill them manually
  }

  Widget _buildEditInfoTile({
    required String leadingIcon,
    required String title,
    required String subTitle,
    required VoidCallback onTap,
    required String trailingIcon,
    required BuildContext context,
    required HmgServicesViewModel hmgServicesVM,
    Color? iconColor,
  }) {
    return InkWell(
      onTap: onTap,
      child: Row(
        children: [
          Expanded(
            child: Row(
              children: [
                Container(
                  height: 40.h,
                  width: 40.h,
                  margin: EdgeInsetsDirectional.only(end: 10.h),
                  padding: EdgeInsets.all(8.h),
                  decoration: RoundedRectangleBorder().toSmoothCornerDecoration(borderRadius: 12.r, color: AppColors.greyColor),
                  child: Utils.buildSvgWithAssets(icon: leadingIcon, iconColor: iconColor),
                ),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    title.toText14(isBold: true),
                    subTitle.toText12(color: AppColors.primaryRedColor, isBold: true, isEnglishOnly: true).toShimmer2(
                        isShow: (leadingIcon == AppAssets.rulerIcon || leadingIcon == AppAssets.weightScale) && hmgServicesVM.isVitalSignLoading),
                  ],
                ),
              ],
            ),
          ),
          Utils.buildSvgWithAssets(icon: trailingIcon, height: 24.h, width: 24.h),
        ],
      ),
    );
  }

  Widget _getDivider() {
    return Divider(
      color: AppColors.dividerColor,
    ).paddingSymmetrical(0, 8.h);
  }

  /// Convert internal gender key to localized display string
  String _getLocalizedGender(String? genderKey, BuildContext context) {
    if (genderKey == null) return LocaleKeys.notSet.tr(context: context);

    final lowerKey = genderKey.toLowerCase();
    if (lowerKey == "male") {
      return LocaleKeys.malE.tr(context: context);
    } else if (lowerKey == "female") {
      return LocaleKeys.femaleGender.tr(context: context);
    } else {
      return genderKey; // Return as-is if not recognized
    }
  }

  @override
  Widget build(BuildContext context) {
    AppState appState = getIt.get<AppState>();

    String name = "";
    int? userAgeFromDOB;
    if (appState.isAuthenticated) {
      final user = appState.getAuthenticatedUser();
      name = "${user!.firstName!} ${user.lastName!} ";

      // Calculate age from authenticated user's DOB if available
      if (user.dateofBirth != null && user.dateofBirth!.isNotEmpty) {
        try {
          DateTime dob = DateUtil.convertStringToDate(user.dateofBirth!);
          final now = DateTime.now();
          int age = now.year - dob.year;
          if (now.month < dob.month || (now.month == dob.month && now.day < dob.day)) {
            age--;
          }
          userAgeFromDOB = age;
          getIt.get<SymptomsCheckerViewModel>().setSelectedAge(userAgeFromDOB);
        } catch (e) {
          // If date parsing fails, ignore
        }
      }
    } else {
      name = "";

      /// as per the mahmooud instruction, if user is not authenticated, we will not show any name in the greeting message
    }

    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: Consumer2<SymptomsCheckerViewModel, HmgServicesViewModel>(
        builder: (context, viewModel, hmgServicesVM, child) {
          // Check if any field is empty
          bool hasEmptyFields = viewModel.selectedGender == null ||
              viewModel.selectedAge == null ||
              viewModel.selectedHeight == null ||
              viewModel.selectedWeight == null;

          // Get display values
          String genderText = _getLocalizedGender(viewModel.selectedGender, context);
          // Show age calculated from DOB (prefer viewModel's age, fallback to calculated from user's DOB)
          int? displayAge = viewModel.selectedAge ?? userAgeFromDOB;
          String ageText = displayAge != null ? "$displayAge ${LocaleKeys.years.tr(context: context)}" : LocaleKeys.notSet.tr(context: context);

          String heightText = (viewModel.selectedHeight != null && viewModel.selectedHeight != 0)
              ? "${viewModel.selectedHeight!.round()} ${viewModel.isHeightCm ? LocaleKeys.cm.tr() : LocaleKeys.ft.tr()}"
              : LocaleKeys.notSet.tr(context: context);

          String weightText = (viewModel.selectedWeight != null && viewModel.selectedWeight != 0)
              ? "${viewModel.selectedWeight!.round()} ${viewModel.isWeightKg ? LocaleKeys.kg.tr() : LocaleKeys.lb.tr()}"
              : LocaleKeys.notSet.tr(context: context);

          return Column(
            children: [
              Expanded(
                child: CollapsingListView(
                  title: LocaleKeys.symptomsChecker.tr(context: context),
                  isLeading: true,
                  child: SingleChildScrollView(
                    child: Column(
                      children: [
                        Container(
                          width: double.infinity,
                          decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r),
                          padding: EdgeInsets.symmetric(vertical: 24.h, horizontal: 16.w),
                          child: Column(
                            children: [
                              LocaleKeys.helloIsYourInformationUpToDate
                                  .tr(namedArgs: {'name': name})
                                  .toText16(
                                    weight: FontWeight.w600,
                                    color: AppColors.textColor,
                                  )
                                  .onPress(() {
                                    context.navigateWithName(AppRoutes.userConsentScreen);
                                  }),
                              SizedBox(height: 32.h),
                              _buildEditInfoTile(
                                  context: context,
                                  leadingIcon: AppAssets.genderIcon,
                                  title: LocaleKeys.gender.tr(context: context),
                                  subTitle: genderText,
                                  onTap: () {
                                    viewModel.setUserInfoPage(0, isSinglePageEdit: true);
                                    context.navigateWithName(AppRoutes.userInfoFlowManager);
                                  },
                                  trailingIcon: AppAssets.edit_icon,
                                  hmgServicesVM: hmgServicesVM),
                              _getDivider(),
                              _buildEditInfoTile(
                                  context: context,
                                  leadingIcon: AppAssets.calendarGrey,
                                  title: LocaleKeys.age.tr(context: context),
                                  subTitle: ageText,
                                  iconColor: AppColors.greyTextColor,
                                  onTap: () {
                                    viewModel.setUserInfoPage(1, isSinglePageEdit: true);
                                    context.navigateWithName(AppRoutes.userInfoFlowManager);
                                  },
                                  trailingIcon: AppAssets.edit_icon,
                                  hmgServicesVM: hmgServicesVM),
                              _getDivider(),
                              _buildEditInfoTile(
                                  context: context,
                                  leadingIcon: AppAssets.rulerIcon,
                                  title: LocaleKeys.height.tr(context: context),
                                  subTitle: heightText,
                                  onTap: () {
                                    viewModel.setUserInfoPage(2, isSinglePageEdit: true);
                                    context.navigateWithName(AppRoutes.userInfoFlowManager);
                                  },
                                  trailingIcon: AppAssets.edit_icon,
                                  hmgServicesVM: hmgServicesVM),
                              _getDivider(),
                              _buildEditInfoTile(
                                  context: context,
                                  leadingIcon: AppAssets.weightScale,
                                  title: LocaleKeys.weight.tr(context: context),
                                  subTitle: weightText,
                                  onTap: () {
                                    viewModel.setUserInfoPage(3, isSinglePageEdit: true);
                                    context.navigateWithName(AppRoutes.userInfoFlowManager);
                                  },
                                  trailingIcon: AppAssets.edit_icon,
                                  hmgServicesVM: hmgServicesVM),
                            ],
                          ),
                        ),
                      ],
                    ).paddingAll(24.w),
                  ),
                ),
              ),
              _buildBottomCard(context, hasEmptyFields),
            ],
          );
        },
      ),
    );
  }

  Widget _buildBottomCard(BuildContext context, bool hasEmptyFields) {
    return Container(
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r),
      child: SafeArea(
        top: false,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            SizedBox(height: 24.h),
            Row(
              children: [
                Expanded(
                  child: CustomButton(
                    text: LocaleKeys.noEditAll.tr(context: context),
                    icon: AppAssets.edit_icon,
                    iconColor: AppColors.primaryRedColor,
                    onPressed: () {
                      context.read<SymptomsCheckerViewModel>().setUserInfoPage(0, isSinglePageEdit: false);
                      context.navigateWithName(AppRoutes.userInfoFlowManager);
                    },
                    backgroundColor: AppColors.primaryRedColor.withValues(alpha: 0.11),
                    borderColor: Colors.transparent,
                    textColor: AppColors.primaryRedColor,
                    fontSize: 16.f,
                    iconSize: 20.w,
                  ),
                ),
                SizedBox(width: 12.w),
                Expanded(
                  child: CustomButton(
                    text: LocaleKeys.yesItIs.tr(context: context),
                    icon: AppAssets.tickIcon,
                    iconColor: hasEmptyFields ? AppColors.greyTextColor : AppColors.whiteColor,
                    isDisabled: getIt.get<HmgServicesViewModel>().isVitalSignLoading || hasEmptyFields,
                    onPressed: hasEmptyFields
                        ? () {} // Empty function for disabled state
                        : () => context.navigateWithName(AppRoutes.organSelectorPage),
                    backgroundColor: hasEmptyFields ? AppColors.greyLightColor : AppColors.primaryRedColor,
                    borderColor: hasEmptyFields ? AppColors.greyLightColor : AppColors.primaryRedColor,
                    textColor: hasEmptyFields ? AppColors.greyTextColor : AppColors.whiteColor,
                    fontSize: 16.f,
                    iconSize: 20.w,
                  ),
                ),
              ],
            ),
            SizedBox(height: 24.h),
          ],
        ).paddingSymmetrical(24.w, 0),
      ),
    );
  }
}
