import 'dart:async';
import 'package:fis_common/event/event_type.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/lab/color/lab_colors.dart';
import 'package:flyinsono/lab/pages/lab_image/controller.dart';

class ImagePlaySlider extends StatefulWidget {
  const ImagePlaySlider({
    super.key,
    required this.minValue,
    required this.maxValue,
    required this.currentValue,
    this.onChanged,
    this.onSleepHandler,
  });

  final FEventHandler<bool>? onSleepHandler;
  final int minValue;
  final int maxValue;
  final int currentValue;
  final ValueChanged<int>? onChanged;

  @override
  State<StatefulWidget> createState() {
    return ImagePlaySliderState();
  }
}

class ImagePlaySliderState extends State<ImagePlaySlider> {
  late int _currentValue;
  Timer? _timer;
  bool _isPause = false;
  @override
  void initState() {
    super.initState();
    widget.onSleepHandler?.addListener(_onSleep);
    _currentValue = widget.currentValue;
    _startTimer();
  }

  @override
  void didUpdateWidget(ImagePlaySlider oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.currentValue != _currentValue) {
      _currentValue = widget.currentValue;
    }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    print('SecondScreen didChangeDependencies');
  }

  @override
  void dispose() {
    widget.onSleepHandler?.removeListener(_onSleep);
    _stopTimer();
    super.dispose();
  }

  void _startTimer() {
    if (_timer == null || !_timer!.isActive) {
      _timer = Timer.periodic(Duration(milliseconds: 50), (Timer timer) {
        if (_currentValue == widget.maxValue) {
          _currentValue = widget.minValue - 1;
        }
        if (mounted) {
          setState(() {
            _currentValue =
                (_currentValue + 1).clamp(widget.minValue, widget.maxValue);
          });
          widget.onChanged?.call(_currentValue);
        }
      });
    }
  }

  void _stopTimer() {
    if (_timer != null && _timer!.isActive) {
      _timer!.cancel();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Row(
        children: [
          Material(
            color: Colors.transparent,
            child: Container(
              margin: const EdgeInsets.only(left: 5),
              child: InkWell(
                borderRadius: BorderRadius.circular(3),
                hoverColor: LabColors.base400,
                onTap: () {
                  setState(() {
                    _currentValue = (_currentValue - 1)
                        .clamp(widget.minValue, widget.maxValue);
                  });
                  widget.onChanged?.call(_currentValue);
                },
                child: Padding(
                  padding: const EdgeInsets.symmetric(vertical: 4),
                  child: Icon(
                    Icons.keyboard_arrow_left_rounded,
                    color: LabColors.base800,
                    size: 28,
                  ),
                ),
              ),
            ),
          ),
          Material(
            color: Colors.transparent,
            child: Container(
              margin: const EdgeInsets.only(right: 5),
              child: InkWell(
                borderRadius: BorderRadius.circular(3),
                hoverColor: LabColors.base400,
                onTap: () {
                  setState(() {
                    _isPause = !_isPause;
                  });
                  if (_isPause) {
                    _stopTimer();
                  } else {
                    _startTimer();
                  }
                },
                child: Padding(
                  padding: const EdgeInsets.symmetric(vertical: 4),
                  child: Icon(
                    _isPause ? Icons.play_arrow : Icons.pause,
                    color: LabColors.base800,
                    size: 28,
                  ),
                ),
              ),
            ),
          ),
          Material(
            color: Colors.transparent,
            child: Container(
              margin: const EdgeInsets.only(right: 5),
              child: InkWell(
                borderRadius: BorderRadius.circular(3),
                hoverColor: LabColors.base400,
                onTap: () {
                  setState(() {
                    _currentValue = (_currentValue + 1)
                        .clamp(widget.minValue, widget.maxValue);
                  });
                  widget.onChanged?.call(_currentValue);
                },
                child: Padding(
                  padding: const EdgeInsets.symmetric(vertical: 4),
                  child: Icon(
                    Icons.keyboard_arrow_right_rounded,
                    color: LabColors.base800,
                    size: 28,
                  ),
                ),
              ),
            ),
          ),
          Expanded(
            child: SliderTheme(
              data: SliderThemeData(
                trackHeight: 8,
                thumbShape: const RoundSliderThumbShape(
                  enabledThumbRadius: 12,
                  elevation: 3,
                  pressedElevation: 3,
                ),
                overlayShape: const RoundSliderOverlayShape(
                  overlayRadius: 0,
                ),
                thumbColor: LabColors.base700,
                overlayColor: Colors.transparent,
                activeTrackColor: LabColors.base700,
                inactiveTrackColor: LabColors.base400,
                activeTickMarkColor: LabColors.base400,
                inactiveTickMarkColor: LabColors.base400,
              ),
              child: Slider(
                value: _currentValue.toDouble(),
                min: widget.minValue.toDouble(),
                max: widget.maxValue.toDouble(),
                divisions: widget.maxValue - widget.minValue,
                // activeColor: LabColors.base600,
                // inactiveColor: LabColors.base100,
                onChanged: (double value) {
                  setState(() {
                    _currentValue = value.round();
                  });
                  widget.onChanged?.call(_currentValue);
                },
              ),
            ),
          ),
          SizedBox(width: 10),
        ],
      ),
    );
  }

  void _onSleep(Object sender, bool e) {
    if (mounted) {
      setState(() {
        _isPause = true;
      });
    }
    _stopTimer();
  }
}
