import 'dart:developer';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/core/app_export.dart';
import 'package:hmg_patient_app_new/extensions/route_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/presentation/symptoms_checker/user_info_selection/pages/age_selection_page.dart';
import 'package:hmg_patient_app_new/presentation/symptoms_checker/user_info_selection/pages/gender_selection_page.dart';
import 'package:hmg_patient_app_new/presentation/symptoms_checker/user_info_selection/pages/height_selection_page.dart';
import 'package:hmg_patient_app_new/presentation/symptoms_checker/user_info_selection/pages/weight_selection_page.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';

/// Manages the user info selection flow with PageView
/// Only the page content changes, header and footer remain fixed
class UserInfoFlowManager extends StatefulWidget {
  const UserInfoFlowManager({super.key});

  @override
  State<UserInfoFlowManager> createState() => _UserInfoFlowManagerState();
}

class _UserInfoFlowManagerState extends State<UserInfoFlowManager> {
  late PageController _pageController;
  late SymptomsCheckerViewModel _viewModel;

  // Get localized page titles
  List<String> _getPageTitles(BuildContext context) {
    return [
      LocaleKeys.genderSymptoms.tr(context: context),
      LocaleKeys.dateOfBirthSymptoms.tr(context: context),
      LocaleKeys.heightSymptoms.tr(context: context),
      LocaleKeys.weightSymptoms.tr(context: context),
    ];
  }

  @override
  void initState() {
    super.initState();
    _viewModel = context.read<SymptomsCheckerViewModel>();
    // Initialize PageController with the current page from ViewModel
    _pageController = PageController(initialPage: _viewModel.userInfoCurrentPage);
  }

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

  void _onNext() {
    // If in single page edit mode, just save and go back
    if (_viewModel.isSinglePageEditMode) {
      context.pop();
      return;
    }

    // Otherwise, continue with normal flow
    if (_viewModel.userInfoCurrentPage < 3) {
      _viewModel.nextUserInfoPage();
      _pageController.animateToPage(
        _viewModel.userInfoCurrentPage,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
    } else {
      _submitUserInfo();
    }
  }

  void _onPrevious() {
    if (_viewModel.userInfoCurrentPage > 0) {
      _viewModel.previousUserInfoPage();
      _pageController.animateToPage(
        _viewModel.userInfoCurrentPage,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
    } else {
      context.pop();
    }
  }

  void _submitUserInfo() {
    final userInfo = _viewModel.getUserInfoData();

    // Log user info
    log('User Info Submitted:');
    log('Gender: ${userInfo['gender']}');
    log('Age: ${userInfo['age']}');
    log('Height: ${userInfo['height']} ${userInfo['heightUnit']}');
    log('Weight: ${userInfo['weight']} ${userInfo['weightUnit']}');

    // TODO: Save user info to backend/storage

    // Navigate to symptoms checker or next screen
    context.pop();
  }

  Widget _buildProgressBar() {
    return Consumer<SymptomsCheckerViewModel>(
      builder: (BuildContext context, viewModel, child) {
        return Row(
          children: List.generate(4, (index) {
            final isCompleted = index < viewModel.userInfoCurrentPage;
            final isCurrentStep = index == viewModel.userInfoCurrentPage;

            return Expanded(
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 6.w),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(8.r),
                  child: Stack(
                    children: [
                      // Background (grey)
                      Container(
                        height: 4.h,
                        decoration: BoxDecoration(
                          color: AppColors.greyLightColor,
                          borderRadius: BorderRadius.circular(8.r),
                        ),
                      ),
                      // Animated red fill from left to right
                      TweenAnimationBuilder<double>(
                        duration: const Duration(milliseconds: 400),
                        curve: Curves.easeInOut,
                        tween: Tween<double>(
                          begin: 0.0,
                          end: isCompleted
                              ? 1.0
                              : isCurrentStep
                                  ? 1.0
                                  : 0.0,
                        ),
                        builder: (context, value, child) {
                          return FractionallySizedBox(
                            alignment: Alignment.centerLeft,
                            widthFactor: value,
                            child: Container(
                              height: 4.h,
                              decoration: BoxDecoration(
                                color: AppColors.primaryRedColor,
                                borderRadius: BorderRadius.circular(8.r),
                                boxShadow: isCurrentStep && value > 0
                                    ? [
                                        BoxShadow(
                                          color: AppColors.primaryRedColor.withValues(alpha: 0.4),
                                          blurRadius: 8.r,
                                          spreadRadius: 1.r,
                                        ),
                                      ]
                                    : null,
                              ),
                            ),
                          );
                        },
                      ),
                    ],
                  ),
                ),
              ),
            );
          }),
        );
      },
    );
  }

  Widget _buildStickyBottomCard() {
    return Consumer<SymptomsCheckerViewModel>(builder: (BuildContext context, viewModel, child) {
      bool isLastPage = viewModel.isUserInfoLastPage;
      bool isFirstPage = viewModel.isUserInfoFirstPage;
      bool isSingleEdit = viewModel.isSinglePageEditMode;

      return Container(
        decoration: BoxDecoration(
          color: AppColors.whiteColor,
          borderRadius: BorderRadius.vertical(top: Radius.circular(24.r)),
        ),
        padding: EdgeInsets.only(left: 24.w, right: 24.w, top: 16.h, bottom: 24.h),
        child: SafeArea(
          top: false,
          child: isSingleEdit
              ? // Single page edit mode - show only Save button
              CustomButton(
                  text: LocaleKeys.save.tr(context: context),
                  isDisabled: !(viewModel.isCurrentUserInfoPageValid),
                  onPressed: () => viewModel.isCurrentUserInfoPageValid ? _onNext() : () {},
                  backgroundColor:
                      viewModel.isCurrentUserInfoPageValid ? AppColors.primaryRedColor : AppColors.primaryRedColor.withValues(alpha: 0.5),
                  borderColor: viewModel.isCurrentUserInfoPageValid ? AppColors.primaryRedColor : AppColors.primaryRedColor.withValues(alpha: 0.5),
                  textColor: AppColors.whiteColor,
                  fontSize: 16.f,
                )
              : // Complete flow mode - show Previous/Next buttons
              Row(
                  children: [
                    if (!isFirstPage) ...[
                      Expanded(
                        child: CustomButton(
                          text: LocaleKeys.previous.tr(context: context),
                          onPressed: _onPrevious,
                          backgroundColor: AppColors.primaryRedColor.withValues(alpha: 0.11),
                          borderColor: Colors.transparent,
                          textColor: AppColors.primaryRedColor,
                          fontSize: 16.f,
                        ),
                      ),
                      SizedBox(width: 12.w),
                    ],
                    Expanded(
                      child: CustomButton(
                        text: isLastPage ? LocaleKeys.submit.tr(context: context) : LocaleKeys.next.tr(context: context),
                        onPressed: _onNext,
                        backgroundColor: AppColors.primaryRedColor,
                        borderColor: AppColors.primaryRedColor,
                        textColor: AppColors.whiteColor,
                        fontSize: 16.f,
                      ),
                    ),
                  ],
                ),
        ),
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    final pageTitles = _getPageTitles(context);

    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: Column(
        children: [
          Expanded(
            child: CollapsingListView(
              physics: NeverScrollableScrollPhysics(),
              title: pageTitles[_viewModel.userInfoCurrentPage],
              isLeading: true,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SizedBox(height: 24.h),
                  // Only show progress bar in complete flow mode
                  if (!_viewModel.isSinglePageEditMode) _buildProgressBar(),
                  if (!_viewModel.isSinglePageEditMode) SizedBox(height: 24.h),
                  SizedBox(
                    height: 600.h,
                    child: PageView(
                      controller: _pageController,
                      physics: const NeverScrollableScrollPhysics(), // Disable swipe
                      onPageChanged: (index) {
                        _viewModel.setUserInfoPage(index);
                      },
                      children: [
                        GenderSelectionPage(
                          selectedGender: _viewModel.selectedGender,
                          onGenderSelected: _viewModel.setGender,
                        ),
                        AgeSelectionPage(
                          selectedAge: _viewModel.selectedAge,
                          onAgeSelected: _viewModel.setAge,
                        ),
                        HeightSelectionPage(),
                        WeightSelectionPage(onWeightChanged: _viewModel.setWeight),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
          _buildStickyBottomCard(),
        ],
      ),
    );
  }
}
