import 'package:animated_toggle_switch/animated_toggle_switch.dart';
import 'package:flutter/material.dart';

typedef LoadFutureCallback = Future<bool> Function(bool value);

class LoadSwitch extends StatefulWidget {
  final bool value;
  final double height;
  final double borderWidth;
  final Color loadingColor;
  final Color selectedColor;
  final Color unselectedColor;

  final LoadFutureCallback future;

  const LoadSwitch(
      {super.key,
      required this.value,
      required this.height,
      required this.future,
      this.borderWidth = 5,
      this.loadingColor = Colors.blue,
      this.selectedColor = Colors.green,
      this.unselectedColor = Colors.red});

  @override
  State<LoadSwitch> createState() => _LoadSwitchState();
}

class _LoadSwitchState extends State<LoadSwitch> {
  bool isSelected = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    isSelected = widget.value;
  }

  @override
  Widget build(BuildContext context) {
    return CustomAnimatedToggleSwitch(
      height: widget.height,
      indicatorSize: Size.square(widget.height),
      current: isSelected,
      values: const [false, true],
      onChanged: (value) async {
        bool newValue = await widget.future(value);
        setState(() {
          isSelected = newValue;
        });
      },
      animationDuration: const Duration(milliseconds: 350),
      // iconArrangement: IconArrangement.overlap,
      // spacing: -16.0,
      wrapperBuilder: (context, global, child) => DecoratedBox(
          decoration: BoxDecoration(
              color: Color.lerp(
                  Color.lerp(widget.unselectedColor, widget.selectedColor,
                      global.position),
                  Colors.grey,
                  global.loadingAnimationValue),
              borderRadius:
                  BorderRadius.all(Radius.circular(widget.height / 2))),
          child: child),
      foregroundIndicatorBuilder: (context, global) {
        return Stack(
          fit: StackFit.expand,
          children: [
            Padding(
              padding: EdgeInsets.all(widget.borderWidth),
              child: const DecoratedBox(
                  decoration: BoxDecoration(
                      shape: BoxShape.circle, color: Colors.white)),
            ),
            Padding(
              padding: EdgeInsets.all(widget.borderWidth / 2),
              child: CircularProgressIndicator(
                strokeWidth: widget.borderWidth,
                color: widget.loadingColor
                    .withOpacity(global.loadingAnimationValue),
              ),
            ),
          ],
        );
      },
      iconBuilder: (context, local, global) => const SizedBox(),
    );
  }
}
