import 'dart:math' as math;
import 'package:flutter/material.dart';
import '../core/theme/app_colors.dart';

class WaveformVisualizer extends StatefulWidget {
  final double width;
  final double height;
  final double amplitude;
  final bool active;

  const WaveformVisualizer({
    super.key,
    this.width = 200,
    this.height = 60,
    this.amplitude = 0.5,
    this.active = true,
  });

  @override
  State<WaveformVisualizer> createState() => _WaveformVisualizerState();
}

class _WaveformVisualizerState extends State<WaveformVisualizer>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 2),
    )..repeat();
  }

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

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _controller,
      builder: (context, _) {
        return CustomPaint(
          size: Size(widget.width, widget.height),
          painter: _WaveformPainter(
            phase: _controller.value * 2 * math.pi,
            amplitude: widget.active ? widget.amplitude : 0.05,
            color: widget.active ? AppColors.royalBlue : Colors.grey,
          ),
        );
      },
    );
  }
}

class _WaveformPainter extends CustomPainter {
  final double phase;
  final double amplitude;
  final Color color;

  _WaveformPainter({
    required this.phase,
    required this.amplitude,
    required this.color,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final mid = size.height / 2;
    final barWidth = 3.0;
    final gap = 2.0;
    final count = (size.width / (barWidth + gap)).floor();

    for (int i = 0; i < count; i++) {
      final x = i * (barWidth + gap);
      final norm = i / count;
      final wave = math.sin(norm * math.pi * 4 + phase);
      final envelope = math.sin(norm * math.pi);
      final h = (wave * envelope * amplitude * mid).abs().clamp(2.0, mid);

      final paint = Paint()
        ..color = color.withValues(alpha: 0.4 + envelope * 0.6)
        ..style = PaintingStyle.fill;

      final rect = RRect.fromRectAndRadius(
        Rect.fromCenter(center: Offset(x + barWidth / 2, mid), width: barWidth, height: h * 2),
        const Radius.circular(2),
      );
      canvas.drawRRect(rect, paint);
    }
  }

  @override
  bool shouldRepaint(covariant _WaveformPainter old) => true;
}
