import 'dart:developer';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hmg_patient_app_new/core/utils/size_utils.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/features/symptoms_checker/models/organ_model.dart';
import 'package:hmg_patient_app_new/presentation/symptoms_checker/widgets/organ_dot_widget.dart';
import 'package:hmg_patient_app_new/presentation/symptoms_checker/widgets/organ_tooltip_widget.dart';

class InteractiveBodyWidget extends StatefulWidget {
  final String bodyImageAsset;
  final List<OrganModel> organs;
  final Set<String> selectedOrganIds;
  final bool isBodyHidden;
  final Function(String organId) onOrganTap;
  final String? tooltipOrganId;
  final bool isArabic;
  final double zoomScale;

  const InteractiveBodyWidget({
    super.key,
    required this.bodyImageAsset,
    required this.organs,
    required this.selectedOrganIds,
    required this.onOrganTap,
    this.isBodyHidden = false,
    this.tooltipOrganId,
    this.isArabic = false,
    this.zoomScale = 1.0,
  });

  @override
  State<InteractiveBodyWidget> createState() => _InteractiveBodyWidgetState();
}

class _InteractiveBodyWidgetState extends State<InteractiveBodyWidget> {
  double? _imageAspectRatio;
  final TransformationController _transformationController = TransformationController();

  @override
  void initState() {
    super.initState();
    _loadImageAspectRatio();
  }

  @override
  void didUpdateWidget(InteractiveBodyWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.bodyImageAsset != widget.bodyImageAsset) {
      _loadImageAspectRatio();
      // Reset zoom when switching views
      _transformationController.value = Matrix4.identity();
    }

    // Update zoom when zoomScale changes
    if (oldWidget.zoomScale != widget.zoomScale) {
      _updateZoom(widget.zoomScale);
    }
  }

  @override
  void dispose() {
    _transformationController.dispose();
    currentZoom = 0.0;
    super.dispose();
  }

  double currentZoom = 0.0;

  Future<void> _loadImageAspectRatio() async {
    final ByteData data = await rootBundle.load(widget.bodyImageAsset);
    final ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List());
    final ui.FrameInfo frameInfo = await codec.getNextFrame();
    final image = frameInfo.image;

    if (mounted) {
      setState(() {
        _imageAspectRatio = image.width / image.height;
      });
    }

    _transformationController.addListener(() {
      currentZoom = _transformationController.value.getMaxScaleOnAxis();
      setState(() {});
    });
  }

  void _updateZoom(double scale) {
    // Keep programmatic zoom centered to avoid drifting the body off-screen.
    final newTransform = Matrix4.identity()..scaleByDouble(scale, scale, 1.0, 1.0);

    _transformationController.value = newTransform;
  }

  @override
  Widget build(BuildContext context) {
    if (_imageAspectRatio == null) {
      return const Center(child: CircularProgressIndicator());
    }

    return LayoutBuilder(
      builder: (context, constraints) {
        return Center(
          child: InteractiveViewer(
            transformationController: _transformationController,
            alignment: Alignment.center,
            panEnabled: true,
            scaleEnabled: true,
            boundaryMargin: currentZoom > 1.2 ? EdgeInsets.all(200.h) : EdgeInsets.zero,
            minScale: 1.0,
            maxScale: 9.0,
            clipBehavior: Clip.none,
            child: AspectRatio(
              aspectRatio: _imageAspectRatio!,
              child: LayoutBuilder(
                builder: (context, imageConstraints) {
                  return Stack(
                    clipBehavior: Clip.none,
                    children: [
                      // Body image
                      Positioned.fill(
                        child: widget.isBodyHidden
                            ? ColorFiltered(
                                colorFilter: ColorFilter.mode(
                                  Colors.black.withValues(alpha: 0.5),
                                  BlendMode.darken,
                                ),
                                child: Utils.buildImgWithAssets(
                                  icon: widget.bodyImageAsset,
                                  fit: BoxFit.fill,
                                ),
                              )
                            : Utils.buildImgWithAssets(
                                icon: widget.bodyImageAsset,
                                fit: BoxFit.fill,
                              ),
                      ),

                      // Organ dots
                      ...widget.organs.map((organ) {
                        final isSelected = widget.selectedOrganIds.contains(organ.id);
                        final dotSize = 18.0;

                        final leftPos = (organ.position.x * imageConstraints.maxWidth) - (dotSize / 2);
                        final topPos = (organ.position.y * imageConstraints.maxHeight) - (dotSize / 2);

                        return Positioned(
                          left: leftPos,
                          top: topPos,
                          child: OrganDot(isSelected: isSelected, onTap: () => widget.onOrganTap(organ.id), size: dotSize),
                        );
                      }),

                      // Tooltip
                      if (widget.tooltipOrganId != null)
                        ...widget.organs.where((organ) => organ.id == widget.tooltipOrganId).map(
                          (organ) {
                            final centerX = organ.position.x * imageConstraints.maxWidth;
                            final centerY = organ.position.y * imageConstraints.maxHeight;
                            return OrganTooltipWidget(
                              organName: organ.getLocalizedDescription(widget.isArabic),
                              position: Offset(centerX, centerY),
                            );
                          },
                        ),
                    ],
                  );
                },
              ),
            ),
          ),
        );
      },
    );
  }
}
