import 'dart:math';

import 'package:fis_ui/index.dart';
import 'package:flutter/material.dart';

class CircleBreathingLight extends FStatefulWidget {
  final double size;
  final Color color;
  final Duration duration;

  const CircleBreathingLight({
    Key? key,
    this.size = 10.0,
    this.color = Colors.green,
    this.duration = const Duration(milliseconds: 1000),
  }) : super(key: key);

  @override
  FState<CircleBreathingLight> createState() => _BreathingLightState();
}

class _BreathingLightState extends FState<CircleBreathingLight>
    with SingleTickerProviderStateMixin {
  late final AnimationController _controller = AnimationController(
    vsync: this,
    duration: widget.duration,
  )..repeat(reverse: true);

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

  @override
  FWidget build(BuildContext context) {
    final animation = CurvedAnimation(
      parent: _controller,
      curve: Curves.fastOutSlowIn,
    );
    return FCustomPaint(
      painter: _BreathingLightPainter(
        color: widget.color,
        animation: animation,
      ),
      size: Size(widget.size, widget.size),
    );
  }
}

class _BreathingLightPainter extends CustomPainter {
  final Color color;
  final Animation<double> animation;

  _BreathingLightPainter({required this.color, required this.animation})
      : super(repaint: animation);

  @override
  void paint(Canvas canvas, Size size) {
    final center = Offset(size.width / 2, size.height / 2);
    final radius = min(size.width, size.height) / 2;
    final strokeWidth = radius * 0.2;
    final progress = animation.value;

    final paint = Paint()
      ..color = color.withOpacity(progress)
      ..strokeWidth = strokeWidth
      ..style = PaintingStyle.fill;

    canvas.drawCircle(center, radius - strokeWidth / 2, paint);
  }

  @override
  bool shouldRepaint(_BreathingLightPainter oldDelegate) =>
      oldDelegate.color != color || oldDelegate.animation != animation;
}
