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_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/cache_consts.dart';
import 'package:hmg_patient_app_new/core/dependencies.dart';
import 'package:hmg_patient_app_new/core/enums.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/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/widgets/interactive_body_widget.dart';
import 'package:hmg_patient_app_new/presentation/symptoms_checker/widgets/pinch_zoom_tutorial_overlay.dart';
import 'package:hmg_patient_app_new/services/cache_service.dart';
import 'package:hmg_patient_app_new/services/dialog_service.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart';
import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart';
import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart';
import 'package:provider/provider.dart';

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

  @override
  State<OrganSelectorPage> createState() => _OrganSelectorPageState();
}

class _OrganSelectorPageState extends State<OrganSelectorPage> with SingleTickerProviderStateMixin {
  static const double _expandedBodyZoomFactor = 1.08;
  static const double _expandedSheetHeightFactor = 0.3;
  static const bool _enableTutorialOverlay = false;
  static const bool _enableSwipeToFlip = false;

  late final AppState _appState;
  late final DialogService dialogService;
  late final CacheService cacheService;
  late final AnimationController _introZoomHintController;
  late final Animation<double> _introZoomHintAnimation;
  bool _showTutorial = false;
  bool _hasPlayedIntroZoomHint = false;

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

    _introZoomHintController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 2000),
    )..addListener(() {
        if (mounted) setState(() {});
      });
    _introZoomHintAnimation = TweenSequence<double>([
      TweenSequenceItem(
        tween: Tween<double>(begin: 1.0, end: 1.25),
        weight: 45,
      ),
      TweenSequenceItem(
        tween: Tween<double>(begin: 1.25, end: 1.0),
        weight: 55,
      ),
    ]).animate(CurvedAnimation(
      parent: _introZoomHintController,
      curve: Curves.easeInOut,
    ));

    _checkAndShowTutorial();
    _playIntroZoomHint();
  }

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

  Future<void> _playIntroZoomHint() async {
    if (_hasPlayedIntroZoomHint) return;
    _hasPlayedIntroZoomHint = true;

    await Future.delayed(const Duration(milliseconds: 700));
    if (!mounted) return;
    _introZoomHintController.forward(from: 0);
  }

  Future<void> _checkAndShowTutorial() async {
    if (!_enableTutorialOverlay) {
      _showTutorial = false;
      return;
    }

    // final hasSeenTutorial = cacheService.getBool(key: CacheConst.organSelectorTutorialShown) ?? false;
    // if (!hasSeenTutorial) {
    // Show tutorial after a short delay to ensure the screen is fully built
    await Future.delayed(const Duration(milliseconds: 500));
    if (mounted) {
      setState(() {
        _showTutorial = true;
      });
    }
    // }
  }

  void _onTutorialComplete() async {
    await cacheService.saveBool(key: CacheConst.organSelectorTutorialShown, value: true);
    setState(() {
      _showTutorial = false;
    });
  }

  void _onNextPressed(SymptomsCheckerViewModel viewModel) async {
    if (!viewModel.validateSelection()) {
      dialogService.showErrorBottomSheet(
        message: LocaleKeys.noOrgansSelected.tr(context: context),
      );
      return;
    }

    // If user is not authenticated, navigate to user consent screen
    if (!_appState.isAuthenticated) {
      context.navigateWithName(AppRoutes.userConsentScreen);
      return;
    }

    // User is authenticated, proceed with API call
    LoaderBottomSheet.showLoader(
      loadingText: LocaleKeys.pleaseWait.tr(context: context),
    );

    // Get fileNo from authenticated user
    final user = _appState.getAuthenticatedUser();
    String? 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 Stack(
      children: [
        Scaffold(
          backgroundColor: AppColors.bgScaffoldColor,
          appBar: _buildAppBar(),
          body: Consumer<SymptomsCheckerViewModel>(
            builder: (context, viewModel, _) {
              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _buildTitle(),
                  SizedBox(height: 8.h),
                  Expanded(
                    child: Stack(
                      children: [
                        SafeArea(
                          top: false,
                          bottom: false,
                          child: _buildBodyViewer(viewModel),
                        ),
                        _buildViewToggleButtons(viewModel),
                        // _buildViewZoomButtons(viewModel),
                        _buildBottomSheet(viewModel),
                      ],
                    ),
                  ),
                ],
              );
            },
          ),
        ),
        // Tutorial overlay
        if (_enableTutorialOverlay && _showTutorial)
          PinchZoomTutorialOverlay(
            onComplete: _onTutorialComplete,
          ),
      ],
    );
  }

  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      backgroundColor: AppColors.bgScaffoldColor,
      elevation: 0,
      leading: Transform.flip(
        flipX: _appState.isArabic(),
        child: IconButton(
          icon: Utils.buildSvgWithAssets(
            icon: AppAssets.forward_top_nav_icon,
            width: 24.w,
            height: 24.h,
          ),
          padding: EdgeInsetsDirectional.only(start: 12, end: 12),
          onPressed: () {
            // Clear selected organs and sheet status when going back
            final viewModel = context.read<SymptomsCheckerViewModel>();
            viewModel.clearAllSelections();
            viewModel.setBottomSheetExpanded(false);
            Navigator.pop(context);
          },
          highlightColor: Colors.transparent,
        ),
      ),
    );
  }

  Widget _buildTitle() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Text(
        LocaleKeys.organSelector.tr(context: context),
        style: TextStyle(
          color: AppColors.textColor,
          fontSize: 22.f,
          fontWeight: FontWeight.w600,
        ),
      ),
    );
  }

  Widget _buildBodyViewer(SymptomsCheckerViewModel viewModel) {
    return GestureDetector(
      onHorizontalDragEnd: !_enableSwipeToFlip
          ? null
          : (details) {
              // Swipe left or right to toggle view
              if (details.primaryVelocity != null) {
                if (details.primaryVelocity! < -200 || details.primaryVelocity! > 200) {
                  viewModel.toggleView();
                }
              }
            },
      child: LayoutBuilder(
        builder: (context, constraints) {
          final bool isExpanded = viewModel.isBottomSheetExpanded;
          final double screenHeight = MediaQuery.of(context).size.height;
          final double extraBottomInset = isExpanded ? screenHeight * _expandedSheetHeightFactor : 0;
          final bool isUserZoomedIn = viewModel.currentZoomScale > 1.01;

          Widget buildInteractiveBody({required bool useExpandedZoom}) {
            return AnimatedSwitcher(
              duration: const Duration(milliseconds: 600),
              transitionBuilder: (child, animation) => _build3DFlipTransition(child, animation),
              switchInCurve: Curves.easeInOut,
              switchOutCurve: Curves.easeInOut,
              child: Builder(
                key: ValueKey<BodyView>(viewModel.currentView),
                builder: (context) {
                  final bool isFemale = (viewModel.selectedGender != null && (viewModel.selectedGender!.toLowerCase() == 'female' || viewModel.selectedGender == 'أنثى'));
                  final double effectiveZoomScale = viewModel.currentZoomScale * _introZoomHintAnimation.value;

                  final String bodyAsset = viewModel.currentView == BodyView.front
                      ? (isFemale ? AppAssets.fullBodyFrontFemale : AppAssets.fullBodyFrontMale)
                      : (isFemale ? AppAssets.fullBodyBackFemale : AppAssets.fullBodyBackMale);

                  final body = InteractiveBodyWidget(
                    bodyImageAsset: bodyAsset,
                    organs: viewModel.currentOrgans,
                    selectedOrganIds: viewModel.selectedOrganIds,
                    onOrganTap: viewModel.toggleOrganSelection,
                    isBodyHidden: viewModel.isBodyHidden,
                    tooltipOrganId: viewModel.tooltipOrganId,
                    isArabic: _appState.isArabic(),
                    zoomScale: effectiveZoomScale,
                  );

                  return body;
                },
              ),
            );
          }

          if (!isExpanded) {
            return Padding(
              padding: EdgeInsets.fromLTRB(16.h, 16.h, 16.h, 60.h),
              child: buildInteractiveBody(useExpandedZoom: false),
            );
          }

          return SingleChildScrollView(
            physics: isExpanded && !isUserZoomedIn ? const ClampingScrollPhysics() : const NeverScrollableScrollPhysics(),
            child: ConstrainedBox(
              constraints: BoxConstraints(
                minHeight: constraints.maxHeight + extraBottomInset,
              ),
              child: Padding(
                padding: EdgeInsets.only(
                  bottom: extraBottomInset,
                  top: 24.h,
                ),
                child: Padding(
                  padding: EdgeInsets.fromLTRB(16.h, 16.h, 16.h, 60.h),
                  child: buildInteractiveBody(useExpandedZoom: true),
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _build3DFlipTransition(Widget child, Animation<double> animation) {
    final rotateAnimation = Tween<double>(begin: 0.5, end: 0.0).animate(
      CurvedAnimation(parent: animation, curve: Curves.easeInOut),
    );

    return AnimatedBuilder(
      animation: rotateAnimation,
      builder: (context, child) {
        final angle = rotateAnimation.value * 3.14159;
        final transform = Matrix4.identity()
          ..setEntry(3, 2, 0.001)
          ..rotateY(angle);

        return Transform(
          transform: transform,
          alignment: Alignment.center,
          child: child,
        );
      },
      child: child,
    );
  }

  Widget _buildViewToggleButtons(SymptomsCheckerViewModel viewModel) {
    return PositionedDirectional(
      start: 16.w,
      top: 36.h,
      child: Column(
        children: [
          _buildToggleButton(
            icon: AppAssets.bodyIcon,
            onTap: viewModel.toggleIsBodyHidden,
          ),
          SizedBox(height: 16.h),
          _buildToggleButton(
            icon: AppAssets.rotateIcon,
            onTap: viewModel.toggleView,
          ),
        ],
      ),
    );
  }

  Widget _buildViewZoomButtons(SymptomsCheckerViewModel viewModel) {
    return PositionedDirectional(
      end: 16.w,
      top: 36.h,
      child: Column(
        children: [
          _buildToggleButton(
            icon: "assets/images/svg/zoom-in.svg",
            onTap: viewModel.toggleZoomIn,
          ),
          SizedBox(height: 16.h),
          _buildToggleButton(
            icon: "assets/images/svg/zoom_out.svg",
            onTap: viewModel.toggleZoomOut,
          ),
        ],
      ),
    );
  }

  Widget _buildToggleButton({required String icon, required VoidCallback onTap}) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: 48.w,
        height: 48.h,
        decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
          color: AppColors.whiteColor,
          borderRadius: 11.r,
        ),
        child: Center(
          child: Utils.buildSvgWithAssets(
            icon: icon,
            width: 25.w,
            height: 25.h,
          ),
        ),
      ),
    );
  }

  Widget _buildBottomSheet(SymptomsCheckerViewModel viewModel) {
    return Positioned(
      left: 0,
      right: 0,
      bottom: 0,
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
        decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r),
        child: SafeArea(
          top: false,
          child: Stack(
            clipBehavior: Clip.none,
            children: [
              Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  if (viewModel.isBottomSheetExpanded) ...[
                    SizedBox(height: 20.h),
                    _buildBottomSheetTitle(),
                    SizedBox(height: 12.h),
                    _buildSelectedOrgansContent(viewModel),
                    SizedBox(height: 16.h),
                    _buildNextButton(viewModel),
                    SizedBox(height: 16.h),
                  ] else
                    SizedBox(height: 20.h),
                ],
              ),
              _buildExpandCollapseButton(viewModel),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildBottomSheetTitle() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Text(
        LocaleKeys.selectedOrgans.tr(context: context),
        style: TextStyle(
          fontSize: 16.f,
          fontWeight: FontWeight.w600,
          color: AppColors.textColor,
        ),
      ),
    );
  }

  Widget _buildSelectedOrgansContent(SymptomsCheckerViewModel viewModel) {
    if (viewModel.selectedOrgans.isEmpty) {
      return Padding(
        padding: EdgeInsets.symmetric(horizontal: 16.w),
        child: Text(
          LocaleKeys.noOrgansSelected.tr(context: context),
          style: TextStyle(
            color: AppColors.greyTextColor,
            fontSize: 14.f,
          ),
        ),
      );
    }

    final isArabic = _appState.isArabic();

    return ConstrainedBox(
      constraints: BoxConstraints(maxHeight: 150.h),
      child: SingleChildScrollView(
        padding: EdgeInsets.symmetric(horizontal: 16.w),
        child: Wrap(
          spacing: 8.w,
          runSpacing: 8.h,
          children: viewModel.selectedOrgans.map((organ) {
            return AppCustomChipWidget(
                labelText: organ.getLocalizedDescription(isArabic),
                backgroundColor: AppColors.secondaryLightRedColor,
                textColor: AppColors.primaryRedColor,
                deleteIcon: AppAssets.cancel,
                deleteIconColor: AppColors.primaryRedColor,
                deleteIconHasColor: false,
                onDeleteTap: () {
                  viewModel.removeOrgan(organ.id);
                });
          }).toList(),
        ),
      ),
    );
  }

  Widget _buildNextButton(SymptomsCheckerViewModel viewModel) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: CustomButton(
        text: LocaleKeys.next.tr(context: context),
        onPressed: () => _onNextPressed(viewModel),
        isDisabled: viewModel.selectedOrgans.isEmpty,
        backgroundColor: AppColors.primaryRedColor,
        textColor: AppColors.whiteColor,
      ),
    );
  }

  Widget _buildExpandCollapseButton(SymptomsCheckerViewModel viewModel) {
    final organCount = viewModel.selectedOrgans.length;
    final showBadge = !viewModel.isBottomSheetExpanded && organCount > 0;

    return PositionedDirectional(
      end: 24.w,
      top: -24.h,
      child: GestureDetector(
        onTap: viewModel.toggleBottomSheet,
        behavior: HitTestBehavior.opaque,
        child: SizedBox(
          width: 70.w,
          height: 70.h,
          child: Stack(
            clipBehavior: Clip.none,
            children: [
              Align(
                alignment: Alignment.center,
                child: Container(
                  width: 48.w,
                  height: 48.h,
                  decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                    color: AppColors.whiteColor,
                    borderRadius: 11.r,
                  ),
                  child: Center(
                    child: Transform.flip(
                      flipX: _appState.isArabic(),
                      child: AnimatedRotation(
                        duration: const Duration(milliseconds: 300),
                        turns: viewModel.isBottomSheetExpanded ? 0.25 : -0.25,
                        child: Utils.buildSvgWithAssets(
                          icon: AppAssets.arrowRight,
                          width: 25.w,
                          height: 25.h,
                        ),
                      ),
                    ),
                  ),
                ),
              ),
              if (showBadge)
                PositionedDirectional(
                  top: 8.h,
                  end: 8.w,
                  child: Container(
                    width: 22.w,
                    height: 22.h,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: AppColors.primaryRedColor,
                      shape: BoxShape.circle,
                      border: Border.all(
                        color: AppColors.whiteColor,
                        width: 1.5,
                      ),
                    ),
                    child: Text(
                      '$organCount',
                      style: TextStyle(
                        color: AppColors.whiteColor,
                        fontSize: 10.f,
                        fontWeight: FontWeight.w700,
                      ),
                    ),
                  ),
                ),
            ],
          ),
        ),
      ),
    );
  }
}
