import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/presentation/water_monitor/widgets/water_splash_progress_widget.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';

class WaterConsumptionProgressWidget extends StatefulWidget {
  /// progress: 0.0 - 100.0
  final double progress;
  final double size;
  final Color? waveColor;
  final double? containerWidth;
  final double? containerHeight;
  final Duration? waveDuration;

  const WaterConsumptionProgressWidget({super.key, required this.progress, this.size = 100, this.waveColor, this.containerWidth, this.containerHeight, this.waveDuration});

  @override
  State<WaterConsumptionProgressWidget> createState() => _WaterConsumptionProgressWidgetState();
}

class _WaterConsumptionProgressWidgetState extends State<WaterConsumptionProgressWidget> with SingleTickerProviderStateMixin {
  late AnimationController _progressController;
  late Animation<double> _progressAnimation;
  double _lastTarget = 0.0;

  @override
  void initState() {
    super.initState();
    _lastTarget = widget.progress;
    _progressController = AnimationController(vsync: this, duration: const Duration(milliseconds: 1200));
    _progressAnimation = Tween<double>(begin: 0, end: widget.progress).animate(CurvedAnimation(parent: _progressController, curve: Curves.easeInOut));
    _progressController.forward();
  }

  @override
  void didUpdateWidget(covariant WaterConsumptionProgressWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    if ((widget.progress - _lastTarget).abs() > 0.01) {
      // animate from current value to new target
      final begin = _progressAnimation.value;
      _progressAnimation =
          Tween<double>(begin: begin, end: widget.progress).animate(CurvedAnimation(parent: _progressController, curve: Curves.easeInOut));
      _progressController
        ..reset()
        ..forward();
      _lastTarget = widget.progress;
    }
  }

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

  @override
  Widget build(BuildContext context) {
    // default to app blue color if none provided
    final blue = widget.waveColor ?? AppColors.blueColor;
    return AnimatedBuilder(
      animation: _progressAnimation,
      builder: (context, child) {
        return WaterWaveProgress(
          progress: _progressAnimation.value,
          size: widget.size,
          showPercentage: false,
          useCircleClip: false,
          waveColor: blue,
          containerWidth: widget.containerWidth,
          containerHeight: widget.containerHeight,
          waveDuration: widget.waveDuration,
          backgroundColor: Colors.transparent,
          progressColor: Colors.transparent,
          textColor: Colors.transparent,
        );
      },
    );
  }
}
