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/utils.dart';
import 'package:hmg_patient_app_new/extensions/route_extensions.dart';
import 'package:hmg_patient_app_new/extensions/widget_extensions.dart';
import 'package:hmg_patient_app_new/features/symptoms_checker/models/resp_models/body_symptom_response_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/services/dialog_service.dart';
import 'package:hmg_patient_app_new/services/navigation_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/chip/custom_selectable_chip.dart';
import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart';
import 'package:provider/provider.dart';

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

  @override
  State<SymptomsSelectorPage> createState() => _SymptomsSelectorPageState();
}

class _SymptomsSelectorPageState extends State<SymptomsSelectorPage> {
  late DialogService dialogService;
  late AppState _appState;
  final TextEditingController _searchController = TextEditingController();

  @override
  void initState() {
    super.initState();
    dialogService = getIt<DialogService>();
    _appState = getIt<AppState>();

    // Listen to search input changes
    _searchController.addListener(() {
      final viewModel = context.read<SymptomsCheckerViewModel>();
      viewModel.filterSymptoms(_searchController.text, isArabic: _appState.isArabic());
    });

    // Initialize symptom groups based on selected organs
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final viewModel = context.read<SymptomsCheckerViewModel>();
      viewModel.initializeSymptomGroups();
    });
  }

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  void _onNextPressed(SymptomsCheckerViewModel viewModel) {
    if (viewModel.hasSelectedSymptoms) {
      // Navigate to triage screen
      context.navigateWithName(AppRoutes.riskFactorsPage);
    } else {
      dialogService.showErrorBottomSheet(
        message: LocaleKeys.pleaseSelectAtLeastOneOptionBeforeProceeding.tr(),
      );
    }
  }

  void _onPreviousPressed() {
    context.pop();
  }

  _buildConfirmationBottomSheet({required BuildContext context, required VoidCallback onConfirm}) {
    return showCommonBottomSheetWithoutHeight(
      title: LocaleKeys.notice.tr(context: context),
      context,
      child: Utils.getWarningWidget(
        loadingText: LocaleKeys.areYouSureYouWantToRestartOrganSelection.tr(),
        isShowActionButtons: true,
        onCancelTap: () => Navigator.pop(context),
        onConfirmTap: () => onConfirm(),
      ),
      callBackFunc: () {},
      isFullScreen: false,
      isCloseButtonVisible: true,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: Consumer<SymptomsCheckerViewModel>(
        builder: (context, viewModel, _) {
          return Column(
            children: [
              Expanded(
                child: CollapsingListView(
                  title: LocaleKeys.symptomsSelector.tr(),
                  leadingCallback: () => _buildConfirmationBottomSheet(
                      context: context,
                      onConfirm: () {
                        context.pop();
                        viewModel.reset(); // Clear all symptoms checker data
                        final navigationService = getIt.get<NavigationService>();
                        // navigationService.replaceAllRoutesAndNavigateToLanding();
                        navigationService.replaceAllRoutesAndNavigateToLandingAuth();
                      }),
                  child: viewModel.isBodySymptomsLoading
                      ? _buildLoadingShimmer()
                      : viewModel.organSymptomsResults.isEmpty
                          ? _buildEmptyState()
                          : Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                SizedBox(height: 16.h),
                                // Inline search field
                                Padding(
                                  padding: EdgeInsets.symmetric(horizontal: 24.w),
                                  child: Container(
                                    decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                                      color: AppColors.whiteColor,
                                      borderRadius: 12.r,
                                    ),
                                    child: TextField(
                                      controller: _searchController,
                                      style: TextStyle(
                                        fontSize: 14.f,
                                        color: AppColors.textColor,
                                        fontFamily: _appState.isArabic() ? 'CairoArabic' : 'Poppins',
                                      ),
                                      decoration: InputDecoration(
                                        hintText: LocaleKeys.search.tr(context: context),
                                        hintStyle: TextStyle(
                                          color: AppColors.greyTextColor,
                                          fontSize: 14.f,
                                        ),
                                        prefixIcon: Icon(
                                          Icons.search,
                                          color: AppColors.greyTextColor,
                                          size: 20.h,
                                        ),
                                        suffixIcon: _searchController.text.isNotEmpty
                                            ? IconButton(
                                                icon: Icon(
                                                  Icons.clear,
                                                  color: AppColors.greyTextColor,
                                                  size: 20.h,
                                                ),
                                                onPressed: () {
                                                  _searchController.clear();
                                                  viewModel.clearSymptomFilter();
                                                },
                                              )
                                            : null,
                                        border: InputBorder.none,
                                        contentPadding: EdgeInsets.symmetric(
                                          horizontal: 16.w,
                                          vertical: 12.h,
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                                SizedBox(height: 16.h),
                                ...viewModel.filteredOrganSymptomsResults.map((organResult) {
                                  // Find matching organ ID from selected organs
                                  String? organId;
                                  String? organName;
                                  final isArabic = _appState.isArabic();
                                  for (var organ in viewModel.selectedOrgans) {
                                    if (organ.name == organResult.name) {
                                      organId = organ.id;
                                      organName = organ.getLocalizedDescription(isArabic);
                                      break;
                                    }
                                  }

                                  if (organId != null && organResult.bodySymptoms != null) {
                                    return Padding(
                                      padding: EdgeInsets.only(bottom: 16.h),
                                      child: _buildSymptomsSelectionCard(
                                        viewModel,
                                        organId,
                                        organName ?? organResult.name ?? '',
                                        organResult.bodySymptoms!,
                                      ),
                                    );
                                  }
                                  return SizedBox.shrink();
                                }),
                              ],
                            ),
                ),
              ),
              if (!viewModel.isBodySymptomsLoading) ...[
                _buildStickyBottomCard(context, viewModel),
              ],
            ],
          );
        },
      ),
    );
  }

  Widget _buildSymptomsSelectionCard(
    SymptomsCheckerViewModel viewModel,
    String organId,
    String organName,
    List<BodySymptom> symptoms,
  ) {
    final isArabic = _appState.isArabic();

    return Container(
      width: double.infinity,
      margin: EdgeInsets.symmetric(horizontal: 24.w),
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r),
      padding: EdgeInsets.symmetric(vertical: 24.h, horizontal: 16.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                child: Text(
                  LocaleKeys.possibleSymptomsRelatedTo.tr(context: context),
                  style: TextStyle(fontSize: 18.f, fontWeight: FontWeight.w600, color: AppColors.textColor),
                ),
              ),
            ],
          ),
          SizedBox(height: 24.h),
          Wrap(
            runSpacing: 12.h,
            spacing: 8.w,
            children: symptoms.map((symptom) {
              final symptomId = symptom.id ?? '';
              final symptomLabel = symptom.getDisplayName(isArabic);
              bool isSelected = viewModel.isSymptomSelected(organId, symptomId);
              return GestureDetector(
                onTap: () => viewModel.toggleSymptomSelection(organId, symptomId),
                child: CustomSelectableChip(
                  label: symptomLabel,
                  selected: isSelected,
                  activeColor: AppColors.primaryRedBorderColor,
                  activeTextColor: AppColors.primaryRedBorderColor,
                  inactiveBorderColor: AppColors.bottomNAVBorder,
                  inactiveTextColor: AppColors.textColor,
                ),
              );
            }).toList(),
          ),
        ],
      ),
    );
  }

  Widget _buildLoadingShimmer() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(height: 16.h),
        // Create 2-3 shimmer cards
        ...List.generate(3, (index) {
          return Padding(
            padding: EdgeInsets.only(bottom: 16.h),
            child: _buildShimmerCard(),
          );
        }),
      ],
    );
  }

  Widget _buildShimmerCard() {
    return Container(
      width: double.infinity,
      margin: EdgeInsets.symmetric(horizontal: 24.w),
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r),
      padding: EdgeInsets.symmetric(vertical: 24.h, horizontal: 16.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Shimmer title
          Container(
            height: 40.h,
            decoration: BoxDecoration(
              color: AppColors.whiteColor,
              borderRadius: BorderRadius.circular(24.r),
            ),
          ).toShimmer2(isShow: true, radius: 24.r),
          SizedBox(height: 16.h),
          // Shimmer chips
          Wrap(
            runSpacing: 12.h,
            spacing: 8.w,
            children: List.generate(4, (index) {
              return Container(
                padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
                decoration: BoxDecoration(
                  color: AppColors.whiteColor,
                  borderRadius: BorderRadius.circular(24.r),
                  border: Border.all(color: AppColors.bottomNAVBorder, width: 1),
                ),
                child: Text(
                  'Loading..',
                  style: TextStyle(fontSize: 14.f, color: AppColors.textColor),
                ),
              ).toShimmer2(isShow: true, radius: 24.r);
            }),
          ),
        ],
      ),
    );
  }

  Widget _buildEmptyState() {
    return Center(
      child: Padding(
        padding: EdgeInsets.all(24.h),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.info_outline, size: 64.h, color: AppColors.greyTextColor),
            SizedBox(height: 16.h),
            Text(
              LocaleKeys.noOrgansSelected.tr(context: context),
              style: TextStyle(
                fontSize: 18.f,
                fontWeight: FontWeight.w600,
                color: AppColors.textColor,
              ),
            ),
            SizedBox(height: 8.h),
            Text(
              LocaleKeys.pleaseGoBackAndSelectOrgansFirst.tr(),
              textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: 14.f,
                color: AppColors.greyTextColor,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildStickyBottomCard(BuildContext context, SymptomsCheckerViewModel viewModel) {
    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.previous.tr(context: context),
                  onPressed: _onPreviousPressed,
                  backgroundColor: AppColors.primaryRedColor.withValues(alpha: 0.11),
                  borderColor: Colors.transparent,
                  textColor: AppColors.primaryRedColor,
                  fontSize: 16.f,
                ),
              ),
              SizedBox(width: 12.w),
              Expanded(
                child: CustomButton(
                  text: LocaleKeys.next.tr(context: context),
                  onPressed: () => _onNextPressed(viewModel),
                  backgroundColor: AppColors.primaryRedColor,
                  borderColor: AppColors.primaryRedColor,
                  textColor: AppColors.whiteColor,
                  fontSize: 16.f,
                ),
              ),
            ], 
          ),
          SizedBox(height: 24.h),
        ],
      ).paddingSymmetrical(24.w, 0),
    );
  }
}
