import 'package:fis_theme/theme.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:flutter/material.dart';
import 'package:fis_common/event/event_type.dart';
import 'package:flyinsono/architecture/define.dart';

class CustomButton<T> extends StatefulWidget implements FPage {
  /// 文案
  final String text;

  /// 点击后的方法
  final ValueCallback onPressed;

  /// 是否选中的状态
  final bool isSelected;

  /// 是否是特殊组件
  final bool isDecreaseAndIncrease;

  /// 按钮可点击
  final bool canExecute;

  /// 按钮里面的数据
  final T data;

  //宽度
  final double width;

  //高度
  final double height;

  ///边框
  final BoxDecoration? decoration;

  //选中时边框
  final BoxDecoration? selectedDecoration;

  final Color? textColor;

  final Color? hoverColor;

  final FEventHandler<bool>? stopEventHandler;

  CustomButton({
    required this.text,
    required this.onPressed,
    required this.data,
    this.isSelected = false,
    this.isDecreaseAndIncrease = false,
    this.canExecute = true,
    this.width = 120,
    this.height = 40,
    this.decoration,
    this.selectedDecoration,
    this.textColor,
    this.hoverColor,
    this.stopEventHandler,
  });

  @override
  _CustomButtonState createState() => _CustomButtonState();

  @override
  String get pageName => 'remote button';
}

class _CustomButtonState extends State<CustomButton>
    with TickerProviderStateMixin {
  Color _hoverColor = Color(0xff2f2f2f);
  bool _isHovering = false;
  @override
  void didUpdateWidget(CustomButton oldWidget) {
    if (oldWidget.isSelected != widget.isSelected) {
      setState(() {});
    }
    super.didUpdateWidget(oldWidget);
  }

  bool _isButtonDisabled = false;
  bool _showProgress = false;
  double _progressValue = 0.0;
  int _currentNum = 0;
  Map<String, dynamic> sendData = {};
  late AnimationController _controller;
  late Animation<double> _animation;

  @override
  void initState() {
    super.initState();
    if (widget.hoverColor != null) {
      _hoverColor = widget.hoverColor!;
    }
    _controller = AnimationController(
      vsync: this,
      duration: Duration(seconds: 2),
    );
    _animation = Tween<double>(begin: 0, end: 1).animate(_controller)
      ..addListener(() {
        setState(() {});
      });
    widget.stopEventHandler?.addListener(_onStopEventHandler);
  }

  @override
  void dispose() {
    _controller.dispose();
    widget.stopEventHandler?.removeListener(_onStopEventHandler);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MouseRegion(
      onEnter: (_) => setState(() => _isHovering = true),
      onExit: (_) => setState(() => _isHovering = false),
      cursor: SystemMouseCursors.click,
      child: Stack(
        children: [
          Container(
            width: widget.width,
            height: widget.height,
            padding: EdgeInsets.symmetric(horizontal: 10),
            decoration: _getBoxDecoration(),
            child: FGestureDetector(
              businessParent: this.widget,
              name: '',
              behavior: HitTestBehavior.translucent,
              onTap: _isButtonDisabled || (!widget.canExecute)
                  ? null
                  : _onButtonPressed,
              child: FCenter(
                child: FText(
                  widget.text,
                  style: TextStyle(
                    color: widget.textColor ?? _getDifferentTextColors(),
                  ),
                ),
              ),
            ),
          ),
          Positioned.fill(
            child: _showProgress && _currentNum != 0
                ? Container(
                    decoration: _getBoxDecoration(),
                    child: Center(
                      child: Text(
                        _currentNum.toString(),
                        style: TextStyle(fontSize: 12.0, color: Colors.blue),
                      ),
                    ),
                  )
                : Container(),
          ),
          Positioned.fill(
            child: _showProgress
                ? Center(
                    child: SizedBox(
                      width: 20.0,
                      height: 20.0,
                      child: CircularProgressIndicator(
                        value: _animation.value,
                        strokeWidth: 3.0,
                        backgroundColor: Colors.white,
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.blue),
                      ),
                    ),
                  )
                : Container(),
          ),
          if (widget.isDecreaseAndIncrease) ...[
            Positioned(
              left: -10,
              top: 0,
              bottom: 0,
              child: FIconButton(
                businessParent: FVirtualPageWidget(''),
                onPressed: () {
                  _currentNum -= 1;
                  _onIncreaseButtonPressed();
                },
                name: '',
                padding: EdgeInsets.zero,
                icon: FIcon(
                  Icons.chevron_left_rounded,
                  color: _getDifferentTextColors(),
                ),
              ),
            ),
            Positioned(
              right: -10,
              top: 0,
              bottom: 0,
              child: FIconButton(
                businessParent: FVirtualPageWidget(''),
                onPressed: () {
                  _currentNum += 1;
                  _onIncreaseButtonPressed();
                },
                name: '',
                padding: EdgeInsets.zero,
                icon: FIcon(
                  Icons.chevron_right_rounded,
                  color: _getDifferentTextColors(),
                ),
              ),
            ),
          ]
        ],
      ),
    );
  }

  BoxDecoration _getBoxDecoration() {
    final normalBoxDecoration = BoxDecoration(
      borderRadius: BorderRadius.circular(8),
      border: Border.all(
        color: FTheme.ins.colorScheme.line,
        width: 0.5,
      ),
      color: _getDifferentColors(),
    );
    if (_isButtonDisabled || (!widget.canExecute)) {
      ///若按钮不可点击，则返回黑色
      return normalBoxDecoration.copyWith(
          color: Color.fromARGB(255, 80, 80, 80));
    }

    BoxDecoration decoration = widget.decoration ?? normalBoxDecoration;
    if (widget.isSelected) {
      decoration = widget.selectedDecoration ?? normalBoxDecoration;
    } else if (_isHovering) {
      decoration = BoxDecoration(
        borderRadius: BorderRadius.circular(8),
        boxShadow: [
          BoxShadow(
            color: Color(0xff1c1c1e).withOpacity(0.4), // 阴影颜色
            offset: Offset(3, 3), // 横向偏移3个像素，纵向偏移3个像素
            blurRadius: 6, // 模糊半径
          ),
        ],
        color: _hoverColor,
      );
    } else {
      decoration = widget.decoration ?? normalBoxDecoration;
    }
    return decoration;
  }

  Color _getDifferentColors() {
    if (widget.isSelected) {
      return Colors.blue;
    } else if (_isButtonDisabled) {
      return Colors.grey;
    } else if (!widget.canExecute) {
      return Color.fromARGB(255, 20, 93, 153);
    } else {
      return Colors.white;
    }
  }

  Color _getDifferentTextColors() {
    if (widget.isSelected ||
        _showProgress ||
        _isButtonDisabled ||
        (!widget.canExecute)) {
      return Colors.white;
    } else {
      return widget.textColor ?? Colors.black;
    }
  }

  Future<void> _onButtonPressed() async {
    setState(() {
      _isButtonDisabled = true;
      _showProgress = true;
    });
    sendData = {
      'Path': widget.data,
    };
    widget.onPressed(sendData);
    await _startAnimation();

    setState(() {
      _isButtonDisabled = false;
      _showProgress = false;
      _progressValue = 0.0;
    });
  }

  Future<void> _onIncreaseButtonPressed() async {
    setState(() {
      _isButtonDisabled = true;
      _showProgress = true;
    });
    // sendData = _currentNum;

    await _startAnimation();
    widget.onPressed(_currentNum);
    setState(() {
      _isButtonDisabled = false;
      _showProgress = false;
      _currentNum = 0;
      // _progressValue = 0.0;
    });
  }

  Future<void> _startAnimation() async {
    try {
      await _controller.reverse(from: 0.0);
      await _controller.forward();
    } on TickerCanceled {
      // the animation got canceled, probably because we were disposed
    }
  }

  void _onStopEventHandler(sender, e) {
    _isButtonDisabled = false;
    _showProgress = false;
    _currentNum = 0;
    setState(() {});
  }
}
