import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SharedPrefButton extends StatefulWidget {
  final Function(bool)? onClick;
  final String spKey;
  final Widget enabledWidget;
  final Widget disabledWidget;
  final bool toggleOnTap;

  SharedPrefButton({
    required this.enabledWidget,
    required this.disabledWidget,
    required this.spKey,
    this.toggleOnTap = true,
    this.onClick,
  });

  @override
  State<StatefulWidget> createState() => _SharedPrefButtonState();
}

class _SharedPrefButtonState extends State<SharedPrefButton> {
  SharedPreferences? _sp;
  bool value = false;

  StreamSubscription? _streamSubscription;

  @override
  void dispose() {
    _streamSubscription?.cancel();
    _streamSubscription = null;
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    SharedPreferences.getInstance().then((v) {
      _sp = v;
      value = _sp!.getBool(widget.spKey) ?? false;
      if (mounted) {
        setState(() {});
      }
    });
    _streamSubscription = Stream.periodic(const Duration(milliseconds: 500),
        (_) => _sp?.getBool(widget.spKey) ?? false).distinct().listen((v) {
      value = v;
      if (mounted) {
        setState(() {});
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: widget.toggleOnTap
          ? () {
              value = !value;
              _sp?.setBool(widget.spKey, value);
              setState(() {});
            }
          : null,
      child: value ? widget.enabledWidget : widget.disabledWidget,
    );
  }
}
