import 'dart:async';
import 'dart:developer';
import 'package:flutter/material.dart';
import '../../../../core/theme/app_theme.dart';
import 'package:audioplayers/audioplayers.dart';

class EmomTimerWidget extends StatefulWidget {
  final int intervalSeconds;
  final int totalSets;
  final int currentSet;
  final VoidCallback onSetComplete;
  final VoidCallback onWorkoutComplete;

  const EmomTimerWidget({
    super.key,
    required this.intervalSeconds,
    required this.totalSets,
    required this.currentSet,
    required this.onSetComplete,
    required this.onWorkoutComplete,
  });

  @override
  State<EmomTimerWidget> createState() => _EmomTimerWidgetState();
}

class _EmomTimerWidgetState extends State<EmomTimerWidget>
    with TickerProviderStateMixin {
  Timer? _timer;
  late int _secondsRemaining;
  bool _isRunning = false;
  late AnimationController _pulseController;
  late AudioPlayer _audioPlayer;

  @override
  void initState() {
    super.initState();
    _secondsRemaining = widget.intervalSeconds;
    _audioPlayer = AudioPlayer();

    _audioPlayer.setAudioContext(
      AudioContext(
        android: AudioContextAndroid(
          isSpeakerphoneOn: false,
          stayAwake: false,
          contentType: AndroidContentType.sonification,
          usageType: AndroidUsageType.notificationEvent,
          audioFocus: AndroidAudioFocus.none,
        ),
        // iOS: AudioContextIOS(
        //   category: AVAudioSessionCategory.ambient,
        //   options: [
        //     AVAudioSessionOptions.mixWithOthers,
        //   ],
        // ),
      ),
    );

    _pulseController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 500),
      lowerBound: 1.0,
      upperBound: 1.1,
    );
  }

  @override
  void dispose() {
    _timer?.cancel();
    _pulseController.dispose();
    _audioPlayer.dispose();
    super.dispose();
  }

  Future<void> _playSound(bool isLong) async {
    try {
      final path = isLong ? 'audio/beep_long.ogg' : 'audio/beep_short.ogg';

      if (_audioPlayer.state == PlayerState.playing) {
        await _audioPlayer.stop();
      }
      await _audioPlayer.play(AssetSource(path));
    } catch (e) {
      log('Audio error: $e');
    }
  }

  void _startTimer() {
    setState(() => _isRunning = true);
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_secondsRemaining > 0) {
        setState(() => _secondsRemaining--);
        if (_secondsRemaining <= 3) {
          _pulseController.forward().then((_) => _pulseController.reverse());
          _playSound(false);
        }
      } else {
        _playSound(true);
        _handleRoundComplete();
      }
    });
  }

  void _handleRoundComplete() {
    if (widget.currentSet < widget.totalSets) {
      widget.onSetComplete();
      setState(() {
        _secondsRemaining = widget.intervalSeconds;
      });
    } else {
      _timer?.cancel();
      setState(() => _isRunning = false);
      widget.onWorkoutComplete();
    }
  }

  void _pauseTimer() {
    _timer?.cancel();
    setState(() => _isRunning = false);
  }

  String _formatTime(int seconds) {
    final m = seconds ~/ 60;
    final s = seconds % 60;
    return '${m.toString().padLeft(2, '0')}:${s.toString().padLeft(2, '0')}';
  }

  @override
  Widget build(BuildContext context) {
    final progress = 1.0 - (_secondsRemaining / widget.intervalSeconds);

    return Column(
      children: [
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
          decoration: BoxDecoration(
            color: AppTheme.primaryColor.withValues(alpha: 0.1),
            borderRadius: BorderRadius.circular(20),
            border: Border.all(color: AppTheme.primaryColor),
          ),
          child: Text(
            'ROUND ${widget.currentSet} / ${widget.totalSets}',
            style: const TextStyle(
              color: AppTheme.primaryColor,
              fontWeight: FontWeight.bold,
              letterSpacing: 1.2,
            ),
          ),
        ),
        const SizedBox(height: 32),
        ScaleTransition(
          scale: _pulseController,
          child: SizedBox(
            width: 240,
            height: 240,
            child: Stack(
              alignment: Alignment.center,
              children: [
                SizedBox(
                  width: 240,
                  height: 240,
                  child: CircularProgressIndicator(
                    value: 1.0,
                    strokeWidth: 12,
                    color: Colors.white10,
                  ),
                ),
                SizedBox(
                  width: 240,
                  height: 240,
                  child: CircularProgressIndicator(
                    value: progress,
                    strokeWidth: 12,
                    color: _secondsRemaining <= 3
                        ? AppTheme.errorColor
                        : AppTheme.primaryColor,
                    strokeCap: StrokeCap.round,
                  ),
                ),
                Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      _formatTime(_secondsRemaining),
                      style: Theme.of(context).textTheme.displayLarge?.copyWith(
                            fontSize: 64,
                            color: Colors.white,
                            fontFamily: 'monospace',
                          ),
                    ),
                    if (!_isRunning &&
                        widget.currentSet == 1 &&
                        _secondsRemaining == widget.intervalSeconds)
                      Text(
                        'READY?',
                        style: Theme.of(context)
                            .textTheme
                            .labelLarge
                            ?.copyWith(color: Colors.grey),
                      )
                    else if (!_isRunning)
                      Text(
                        'PAUSED',
                        style: Theme.of(context)
                            .textTheme
                            .labelLarge
                            ?.copyWith(color: AppTheme.errorColor),
                      ),
                  ],
                ),
              ],
            ),
          ),
        ),
        const SizedBox(height: 48),
        if (!_isRunning)
          SizedBox(
            width: double.infinity,
            height: 56,
            child: ElevatedButton.icon(
              onPressed: _startTimer,
              icon: const Icon(Icons.play_arrow),
              label: Text(widget.currentSet == 1 &&
                      _secondsRemaining == widget.intervalSeconds
                  ? 'IGNITE ENGINE'
                  : 'RESUME'),
              style: ElevatedButton.styleFrom(
                backgroundColor: AppTheme.successColor,
                foregroundColor: Colors.white,
              ),
            ),
          )
        else
          SizedBox(
            width: double.infinity,
            height: 56,
            child: OutlinedButton.icon(
              onPressed: _pauseTimer,
              icon: const Icon(Icons.pause),
              label: const Text('PAUSE'),
              style: OutlinedButton.styleFrom(
                foregroundColor: AppTheme.errorColor,
                side: const BorderSide(color: AppTheme.errorColor),
              ),
            ),
          ),
      ],
    );
  }
}
