import 'package:fis_ui/index.dart';
import 'package:fis_ui/interface/interactive_container.dart';
import 'package:flutter/material.dart';

/// 音量调节控件 0-100
class StatefulSlider extends FStatefulWidget {
  final ValueCallback<int> onVolumeChanged;
  final ValueCallback<int> onVolumeChanging;
  final int initVolume;
  StatefulSlider(
      {required this.onVolumeChanged,
      required this.onVolumeChanging,
      required this.initVolume});

  @override
  _StatefulSliderState createState() => _StatefulSliderState();
}

class VolumeSlider extends FStatefulWidget implements FInteractiveContainer {
  final void Function(int) onVolumeChanged;
  final FWidget child;
  final int initVolume;
  final double extraOffsetX;

  VolumeSlider(
      {this.initVolume = 100,
      this.extraOffsetX = 0,
      required this.child,
      required this.onVolumeChanged});

  @override
  String get pageName => "VolumeSlider";

  @override
  FState<FStatefulWidget> createState() {
    return _VolumeSliderState();
  }
}

class _StatefulSliderState extends FState<StatefulSlider> {
  int _volume = 100;

  @override
  FWidget build(BuildContext context) {
    return FRow(
      children: [
        FExpanded(
          child: FSlider(
            min: 0,
            max: 100,
            divisions: 100,
            value: _volume.toDouble(),
            onChanged: (value) {
              widget.onVolumeChanging(value.toInt());
              setState(() {
                _volume = value.toInt();
              });
            },
            onChangeEnd: (value) {
              widget.onVolumeChanged.call(value.toInt());
            },
          ),
        ),
        FContainer(
          width: 30,
          child: FText(
            "$_volume",
            style: TextStyle(color: Colors.white),
          ),
        ),
      ],
    );
  }

  @override
  void initState() {
    super.initState();
    _volume = widget.initVolume;
  }

  @override
  void didUpdateWidget(StatefulSlider oldWidget) {
    super.didUpdateWidget(oldWidget);
    _volume = widget.initVolume;
  }
}

class _VolumeSliderState extends FState<VolumeSlider> {
  /// 音量调节控件高度
  static const double _height = 30;

  /// 音量调节控件宽度
  static const double _width = 200;
  OverlayEntry? _entry;
  int _volume = 100;

  /// 滑动时最后一次的音量值
  int _lastChangedVolume = 100;

  /// 当前是否移入Overlay
  bool _isEnterOverlay = false;

  /// 当前是否移入target
  bool _isEnterTarget = false;

  @override
  FWidget build(BuildContext context) {
    return FMouseRegion(
      onEnter: (event) {
        _showTooltip();
      },
      onExit: (event) {
        _hideTooltip();
      },
      child: FContainer(
        child: widget.child,
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    if (_entry != null) {
      _entry?.remove();
      _entry = null;
    }
  }

  @override
  void initState() {
    super.initState();
    _volume = widget.initVolume;
    _lastChangedVolume = widget.initVolume;
  }

  /// 创建 Overlay 组件
  Widget _buildOverlay(Offset offset) {
    return Directionality(
      textDirection: Directionality.of(context),
      child: Positioned(
        left: offset.dx,
        bottom: offset.dy,
        child: FMouseRegion(
          onEnter: (event) {
            _keepTooltip();
          },
          onExit: (event) {
            _cancelKeepTooltip();
          },
          child: FContainer(
            decoration: BoxDecoration(
              color: Colors.black.withOpacity(0.5),
              borderRadius: BorderRadius.circular(_height / 2),
            ),
            margin: EdgeInsets.only(bottom: 5),
            width: _width,
            height: _height,
            child: StatefulSlider(
              initVolume: _volume,
              onVolumeChanged: (value) {
                setState(() {
                  _volume = value;
                });
                widget.onVolumeChanged.call(_volume);
              },
              onVolumeChanging: (value) {
                if (value == _lastChangedVolume) return;
                _lastChangedVolume = value;
              },
            ),
          ),
        ),
      ),
    );
  }

  /// 取消保持显示 Tooltip
  void _cancelKeepTooltip() {
    _isEnterOverlay = false;
  }

  /// 创建新的 OverlayEntry
  void _createNewEntry() {
    final OverlayState overlayState = Overlay.of(
      context,
      debugRequiredFor: widget,
    );

    final RenderBox target = context.findRenderObject()! as RenderBox;
    final RenderBox targetConatiner =
        overlayState.context.findRenderObject() as RenderBox;
    final Offset targetOffset = target.localToGlobal(
      target.size.center(Offset.zero),
      ancestor: overlayState.context.findRenderObject(),
    );
    final Offset overlayOffset = Offset(
      targetOffset.dx - target.size.width + widget.extraOffsetX,
      targetConatiner.size.height - targetOffset.dy + target.size.height / 2,
    );
    final Widget overlay = _buildOverlay(overlayOffset);
    _entry = OverlayEntry(builder: (BuildContext context) => overlay);
    overlayState.insert(_entry!);
  }

  /// 隐藏 Tooltip
  void _hideTooltip() {
    _isEnterTarget = false;
    _hideTooltipLater();
  }

  /// 立即隐藏
  void _hideTooltipImmediately() {
    if (_entry == null) return;
    if (_entry!.mounted) {
      _entry?.remove();
      _entry = null;
    }
  }

  /// 稍后隐藏
  void _hideTooltipLater() {
    Future.delayed(Duration(milliseconds: 500), () {
      if (_isEnterOverlay || _isEnterTarget) {
        _hideTooltipLater();
        return;
      }
      _preHandleWhenRemove();
      _hideTooltipImmediately();
    });
  }

  /// 保持显示 Tooltip
  void _keepTooltip() {
    _isEnterOverlay = true;
  }

  /// 提前移除的情况下预处理
  void _preHandleWhenRemove() {
    if (_lastChangedVolume != _volume) {
      setState(() {
        _volume = _lastChangedVolume;
      });
      widget.onVolumeChanged.call(_volume);
    }
  }

  /// 显示 Tooltip
  void _showTooltip() {
    _isEnterTarget = true;
    if (_entry != null) return;
    _createNewEntry();
  }
}
