import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hmg_patient_app_new/core/app_export.dart';
import 'package:hmg_patient_app_new/presentation/symptoms_checker/user_info_selection/widgets/triangle_indicator.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';

class WeightScale extends StatefulWidget {
  final double minValue;
  final double maxValue;
  final double initialWeight;
  final bool isKg;
  final ValueChanged<double>? onWeightChanged;

  // Feedback config
  final bool enableHaptic;
  final bool enableSound;
  final Duration feedbackDebounce;

  const WeightScale({
    super.key,
    required this.minValue,
    required this.maxValue,
    required this.initialWeight,
    required this.isKg,
    this.onWeightChanged,
    this.enableHaptic = true,
    this.enableSound = true,
    this.feedbackDebounce = const Duration(milliseconds: 80),
  });

  @override
  State<WeightScale> createState() => _WeightScaleState();
}

class _WeightScaleState extends State<WeightScale> {
  late ScrollController _scrollController;

  // Debounce timer used for playing feedback only after small pause
  Timer? _feedbackTimer;

  int? _lastReportedIndex;
  final double _itemWidth = 8.0; // Width per weight unit

  @override
  void initState() {
    super.initState();
    int initialIndex = (widget.initialWeight - widget.minValue).round();
    final initialOffset = initialIndex * _itemWidth;
    _scrollController = ScrollController(initialScrollOffset: initialOffset);
    _scrollController.addListener(_onScroll);
  }

  void _onScroll() {
    if (!_scrollController.hasClients) return;

    final offset = _scrollController.offset;
    final index = (offset / _itemWidth).round();
    final maxIndex = (widget.maxValue - widget.minValue).round();

    if (index != _lastReportedIndex && index >= 0 && index <= maxIndex) {
      _lastReportedIndex = index;
      final selectedValue = widget.minValue + index;
      widget.onWeightChanged?.call(selectedValue);
      _scheduleFeedback();
    }
  }

  // Schedule haptic + sound feedback with debounce (prevents spamming during fling)
  void _scheduleFeedback() {
    if (!(widget.enableHaptic || widget.enableSound)) return;

    _feedbackTimer?.cancel();
    _feedbackTimer = Timer(widget.feedbackDebounce, () {
      // Haptic
      if (widget.enableHaptic) {
        // selection click is lightweight and appropriate for wheel ticks
        HapticFeedback.selectionClick();
      }
      // Sound
      if (widget.enableSound) {
        // simple system click - note: may be muted by device settings
        SystemSound.play(SystemSoundType.click);
      }
    });
  }

  @override
  void dispose() {
    _feedbackTimer?.cancel();
    _scrollController.removeListener(_onScroll);
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final pointerSize = 20.h;
    final pickerHeight = 100.h;
    final itemCount = (widget.maxValue - widget.minValue).round() + 1;

    return SizedBox(
      height: pickerHeight,
      child: Stack(
        alignment: Alignment.center,
        children: [
          // Horizontal scrollable ruler with gradient fade
          ListView.builder(
            controller: _scrollController,
            scrollDirection: Axis.horizontal,
            physics: const BouncingScrollPhysics(),
            padding: EdgeInsets.symmetric(horizontal: MediaQuery.of(context).size.width / 2),
            itemCount: itemCount,
            itemBuilder: (context, index) {
              final weight = (widget.minValue + index).round();
              final isMainMark = weight % 10 == 0;
              final isMidMark = weight % 5 == 0;

              return SizedBox(
                width: _itemWidth,
                child: Stack(
                  alignment: Alignment.bottomCenter,
                  clipBehavior: Clip.none,
                  children: [
                    // Ruler mark (vertical line)
                    Positioned(
                      bottom: 0,
                      child: Container(
                        width: isMainMark || isMidMark ? 2.5.w : 1.5.w,
                        height: isMainMark
                            ? 40.h
                            : isMidMark
                                ? 30.h
                                : 25.h,
                        decoration: BoxDecoration(
                          color: isMainMark
                              ? AppColors.textColor
                              : isMidMark
                                  ? AppColors.textColorLight
                                  : AppColors.textColorLight.withValues(alpha: 0.5),
                          borderRadius: BorderRadius.circular(2.r),
                        ),
                      ),
                    ),
                    // Number label for main marks
                    if (isMainMark)
                      Positioned(
                        bottom: 45.h,
                        child: Text(
                          weight.toString(),
                          style: TextStyle(
                            fontSize: 11.f,
                            color: AppColors.greyTextColor,
                              fontWeight: FontWeight.w600,
                            height: 1,
                              fontFamily: "Poppins"
                          ),
                          textAlign: TextAlign.center,
                          maxLines: 1,
                          overflow: TextOverflow.visible,
                        ),
                      ),
                  ],
                ),
              );
            },
          ),
          // Triangle indicator pointing to selected value
          Positioned(
            bottom: 0,
            child: TriangleIndicator(
              pointerSize: pointerSize,
              direction: TriangleDirection.up,
            ),
          ),
        ],
      ),
    );
  }
}
