import 'package:flutter/material.dart';
import 'package:guru_utils/datetime/datetime_utils.dart';
import 'package:guru_utils/feedback/feedback_manager.dart';
import 'package:guru_widgets/theme/guru_theme.dart';

/// Created by Haoyi on 2021/9/3

class TapWidget extends StatefulWidget {
  final int throttleTime;
  final VoidCallback onTap;
  final Widget child;
  final bool singleTap;
  final bool inkWell;
  final Color materialColor;
  final BorderRadius? materialBorderRadius;
  final bool isCircle;
  final ShapeBorder? shape;

  const TapWidget(
      {super.key,
      required this.onTap,
      required this.child,
      this.throttleTime = 800,
      this.singleTap = false,
      this.inkWell = false,
      this.isCircle = false,
      this.shape,
      this.materialColor = Colors.transparent,
      this.materialBorderRadius});

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

class _TapState extends State<TapWidget> {
  int _latestTapElapsedInMillis = 0;

  void _processTap({FeedbackCapabilities capabilities = FeedbackCapabilities.sound}) {
    if (_latestTapElapsedInMillis != 0 && widget.singleTap) {
      return;
    }
    if (capabilities != FeedbackCapabilities.disabled) {
      FeedbackManager.instance.perform(FeedbackOccasion.clickButton, capabilities: capabilities);
    }
    final elapsedMs = DateTimeUtils.currentTimeInMillis();
    if (elapsedMs - _latestTapElapsedInMillis > widget.throttleTime) {
      widget.onTap.call();
      _latestTapElapsedInMillis = elapsedMs;
    }
  }

  @override
  Widget build(BuildContext context) {
    final guruTheme = GuruTheme.of(context);
    return widget.inkWell
        ? Material(
            color: widget.materialColor,
            borderRadius: widget.materialBorderRadius,
            shape: widget.shape,
            child: InkWell(
                customBorder: widget.shape,
                onTap: () {
                  _processTap(capabilities: guruTheme.feedbackCapabilities);
                },
                borderRadius: widget.materialBorderRadius,
                child: widget.child))
        : GestureDetector(
            onTap: () {
              _processTap(capabilities: guruTheme.feedbackCapabilities);
            },
            child: widget.child);
  }
}
