import 'package:flutter/material.dart';

class KwAnimatedImagePlaceholder extends StatefulWidget {
  const KwAnimatedImagePlaceholder({
    super.key,
    this.height = double.maxFinite,
    this.width = double.maxFinite,
  });

  final double height;
  final double width;

  @override
  State<KwAnimatedImagePlaceholder> createState() =>
      _KwAnimatedImagePlaceholderState();
}

class _KwAnimatedImagePlaceholderState extends State<KwAnimatedImagePlaceholder>
    with TickerProviderStateMixin {
  late final AnimationController _controller = AnimationController(
    vsync: this,
    duration: Durations.long4,
    animationBehavior: AnimationBehavior.preserve,
  )
    ..forward()
    ..addListener(
      () {
        if (!_controller.isCompleted) return;

        if (_controller.value == 0) {
          _controller.forward();
        } else {
          _controller.reverse();
        }
      },
    );

  late final Animation<double> _opacity = Tween(
    begin: 0.6,
    end: 0.2,
  ).animate(_controller);

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _controller,
      child: DecoratedBox(
        decoration: const BoxDecoration(
          color: Colors.grey,
        ),
        child: SizedBox(
          height: widget.height,
          width: widget.width,
        ),
      ),
      builder: (context, child) {
        return Opacity(
          opacity: _opacity.value,
          child: child,
        );
      },
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}
