import 'package:flutter/material.dart';
import 'package:flyinsono/lab/color/lab_colors.dart';

class ProgressSlider extends StatefulWidget {
  const ProgressSlider({
    super.key,
    required this.min,
    required this.max,
    required this.value,
    this.onChanged,
  });
  final int min;
  final int max;
  final int value;
  final Future<bool> Function(double)? onChanged;

  @override
  State<ProgressSlider> createState() => _ProgressSliderState();
}

class _ProgressSliderState extends State<ProgressSlider> {
  double _value = 0;
  // 手动触发的滑动事件
  bool _isManual = false;

  @override
  void initState() {
    super.initState();
    _value = widget.value.toDouble();
    if (_value < widget.min) {
      _value = widget.min.toDouble();
    }
  }

  @override
  void didUpdateWidget(covariant ProgressSlider oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (_isManual) {
      return;
    }
    if (oldWidget.value != widget.value) {
      _value = widget.value.toDouble();
      if (_value < widget.min) {
        _value = widget.min.toDouble();
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    int? divisions = widget.max - widget.min;
    if (divisions < 1) {
      divisions = 1;
    }
    if (divisions > 60) {
      /// 如果刻度过多，就不显示刻度，不然会卡顿
      divisions = null;
    }
    return Listener(
      onPointerDown: (event) {
        _isManual = true;
      },
      onPointerUp: (event) {
        _isManual = false;
      },
      child: SliderTheme(
        data: SliderThemeData(
          trackHeight: 4,
          thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 10),
          overlayShape: const RoundSliderOverlayShape(overlayRadius: 0),
          thumbColor: LabColors.base600,
          overlayColor: Colors.transparent,
        ),
        child: Slider(
          value: _value,
          onChanged: (value) async {
            if (value == _value) return;

            final result = await widget.onChanged?.call(value);
            if (result == true) {
              setState(() {
                _value = value;
              });
            }
          },
          min: widget.min.toDouble(),
          max: widget.max.toDouble(),
          divisions: divisions,
          activeColor: LabColors.base600,
          // inactiveColor: LabColors.base100,
        ),
      ),
    );
  }
}
