import 'package:flutter/material.dart';
import 'package:flashlink/app/extensions/widget_extension.dart';
import 'package:flashlink/utils/misc.dart';

class ClickOpacity extends StatefulWidget {
  final Widget child;
  final VoidCallback? onTap;
  final VoidCallback? onLongPress;
  final double opacity;
  final Duration duration;
  final bool disabled;
  final bool disableFeedback;

  const ClickOpacity({
    super.key,
    required this.child,
    this.onTap,
    this.onLongPress,
    this.opacity = 0.5,
    this.duration = const Duration(milliseconds: 100),
    this.disabled = false,
    this.disableFeedback = false,
  });

  @override
  State<ClickOpacity> createState() => _ClickOpacityState();
}

class _ClickOpacityState extends State<ClickOpacity> {
  bool _isPressed = false;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTapDown: widget.disableFeedback || widget.disabled
          ? null
          : (_) => _setPressed(true),
      onTapUp: widget.disableFeedback || widget.disabled
          ? null
          : (_) => _setPressed(false),
      onTapCancel: widget.disableFeedback || widget.disabled
          ? null
          : () => _setPressed(false),
      onTap: widget.disabled ? null : widget.onTap,
      onLongPress: widget.disabled ? null : widget.onLongPress,
      child: AnimatedOpacity(
        opacity: _isPressed ? widget.opacity : 1.0,
        duration: widget.duration,
        child: widget.child,
      ),
    ).withClickCursor(!widget.disableFeedback && isDesktop);
  }

  void _setPressed(bool value) {
    if (mounted && _isPressed != value) {
      setState(() {
        _isPressed = value;
      });
    }
  }
}
