import 'package:flutter/material.dart';

class AnimatedColorContainer extends StatefulWidget {
  final Widget child;
  final Color color;
  final Duration duration;
  final BorderRadius? borderRadius;
  final List<BoxShadow>? boxShadow;

  const AnimatedColorContainer({
    super.key,
    required this.child,
    required this.color,
    this.duration = const Duration(milliseconds: 600),
    this.borderRadius,
    this.boxShadow,
  });

  @override
  State<AnimatedColorContainer> createState() => _AnimatedColorContainerState();
}

class _AnimatedColorContainerState extends State<AnimatedColorContainer>
    with TickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _fadeAnimation;
  Color? _previousColor;
  Color? _currentColor;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: widget.duration,
      vsync: this,
    );

    _fadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _controller,
      curve: Curves.easeInOutCubic,
    ));

    _currentColor = widget.color;
  }

  @override
  void didUpdateWidget(AnimatedColorContainer oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.color != widget.color) {
      _previousColor = oldWidget.color;
      _currentColor = widget.color;
      _controller.reset();
      _controller.forward();
    }
  }

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

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _fadeAnimation,
      builder: (context, child) {
        return Container(
          decoration: BoxDecoration(
            borderRadius: widget.borderRadius,
            boxShadow: widget.boxShadow,
          ),
          child: Stack(
            children: [
              Container(
                decoration: BoxDecoration(
                  color: _previousColor ?? _currentColor,
                  borderRadius: widget.borderRadius,
                ),
                child: widget.child,
              ),
              if (_previousColor != null && _fadeAnimation.value > 0)
                Opacity(
                  opacity: _fadeAnimation.value,
                  child: Container(
                    decoration: BoxDecoration(
                      color: _currentColor,
                      borderRadius: widget.borderRadius,
                    ),
                    child: widget.child,
                  ),
                ),
            ],
          ),
        );
      },
    );
  }
}
