import 'dart:async';

import 'package:flutter/material.dart';

class AndroidLockButton extends StatelessWidget {
  const AndroidLockButton({super.key, required this.onLock});

  final VoidCallback onLock;

  @override
  Widget build(BuildContext context) {
    return Material(
      color: const Color(0xB3000000),
      shape: const CircleBorder(),
      child: InkWell(
        customBorder: const CircleBorder(),
        onTap: onLock,
        child: const Padding(
          padding: EdgeInsets.all(8),
          child: Icon(Icons.lock_open, color: Colors.white, size: 22),
        ),
      ),
    );
  }
}

class AndroidLockedOverlay extends StatefulWidget {
  const AndroidLockedOverlay({super.key, required this.onUnlock});

  final VoidCallback onUnlock;

  @override
  State<AndroidLockedOverlay> createState() => _AndroidLockedOverlayState();
}

class _AndroidLockedOverlayState extends State<AndroidLockedOverlay> {
  bool _iconVisible = true;
  Timer? _hideTimer;

  @override
  void initState() {
    super.initState();
    _startTimer();
  }

  void _startTimer() {
    _hideTimer?.cancel();
    _hideTimer = Timer(const Duration(seconds: 3), () {
      if (mounted) setState(() => _iconVisible = false);
    });
  }

  void _onTapBackground() {
    if (!_iconVisible) {
      setState(() => _iconVisible = true);
      _startTimer();
    }
  }

  @override
  void dispose() {
    _hideTimer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: _onTapBackground,
      child: Stack(
        children: [
          Positioned(
            left: 56,
            top: 0,
            bottom: 0,
            child: Center(
              child: AnimatedOpacity(
                opacity: _iconVisible ? 1.0 : 0.0,
                duration: const Duration(milliseconds: 160),
                child: Material(
                  color: const Color(0xB3000000),
                  shape: const CircleBorder(),
                  child: InkWell(
                    customBorder: const CircleBorder(),
                    onTap: _iconVisible ? widget.onUnlock : null,
                    child: const Padding(
                      padding: EdgeInsets.all(8),
                      child: Icon(Icons.lock, color: Colors.white, size: 28),
                    ),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
