import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import '../../ui/theme/app_theme.dart';

class AyuelWaveform extends StatelessWidget {
  final bool isListening;

  const AyuelWaveform({super.key, required this.isListening});

  @override
  Widget build(BuildContext context) {
    if (!isListening) return const SizedBox.shrink();

    return SizedBox(
      height: 60,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: List.generate(5, (index) {
          return Container(
                width: 8,
                height: 20,
                margin: const EdgeInsets.symmetric(horizontal: 4),
                decoration: BoxDecoration(
                  color: AppTheme.primary,
                  borderRadius: BorderRadius.circular(4),
                ),
              )
              .animate(onPlay: (controller) => controller.repeat(reverse: true))
              .scaleY(
                begin: 0.5,
                end: 1.5,
                duration: Duration(milliseconds: 300 + (index * 100)),
                curve: Curves.easeInOut,
              );
        }),
      ),
    );
  }
}

class AyuelTimer extends StatefulWidget {
  final Duration duration;
  final VoidCallback onStop;
  final VoidCallback onFinish; // New callback

  const AyuelTimer({
    super.key,
    required this.duration,
    required this.onStop,
    required this.onFinish, // Required
  });

  @override
  State<AyuelTimer> createState() => _AyuelTimerState();
}

class _AyuelTimerState extends State<AyuelTimer> {
  late final DateTime _endTime;
  bool _finished = false;

  @override
  void initState() {
    super.initState();
    _endTime = DateTime.now().add(widget.duration);
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: Stream.periodic(const Duration(seconds: 1)),
      builder: (context, snapshot) {
        final now = DateTime.now();
        if (now.isAfter(_endTime)) {
          if (!_finished) {
            _finished = true;
            // Delay slightly to avoid build conflicts
            Future.microtask(() => widget.onFinish());
          }
          return _buildTimerDisplay(Duration.zero);
        }
        final remaining = _endTime.difference(now);
        return _buildTimerDisplay(remaining);
      },
    );
  }

  Widget _buildTimerDisplay(Duration remaining) {
    final minutes = remaining.inMinutes.toString().padLeft(2, '0');
    final seconds = (remaining.inSeconds % 60).toString().padLeft(2, '0');
    final progress = remaining.inSeconds / widget.duration.inSeconds;

    return Container(
      padding: const EdgeInsets.all(32),
      decoration: const BoxDecoration(
        color: Colors.white,
        shape: BoxShape.circle,
        boxShadow: [
          BoxShadow(
            color: Colors.black12,
            blurRadius: 20,
            offset: Offset(0, 10),
          ),
        ],
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          SizedBox(
            width: 150,
            height: 150,
            child: Stack(
              fit: StackFit.expand,
              children: [
                CircularProgressIndicator(
                  value: progress,
                  strokeWidth: 8,
                  backgroundColor: AppTheme.surface,
                  color: AppTheme.primary,
                ),
                Center(
                  child: Text(
                    "$minutes:$seconds",
                    style: AppTheme.textTheme.displayLarge?.copyWith(
                      fontSize: 40,
                      fontWeight: FontWeight.bold,
                      color: AppTheme.primary,
                    ),
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(height: 24),
          ElevatedButton(
            onPressed: widget.onStop,
            style: ElevatedButton.styleFrom(
              backgroundColor: AppTheme.surface,
              foregroundColor: AppTheme.textMain,
              elevation: 0,
            ),
            child: const Text("Stop"),
          ),
        ],
      ),
    );
  }
}
