import 'package:flutter/material.dart';
import 'dart:async';
import 'package:slrpg_app/l10n/app_localizations.dart';
import '../../../../core/theme/app_theme.dart';

class TimerWidget extends StatefulWidget {
  final int durationSeconds;
  final VoidCallback? onComplete;
  final bool autoStart;

  const TimerWidget({
    super.key,
    required this.durationSeconds,
    this.onComplete,
    this.autoStart = true,
  });

  @override
  State<TimerWidget> createState() => _TimerWidgetState();
}

class _TimerWidgetState extends State<TimerWidget> with WidgetsBindingObserver {
  late int _secondsRemaining;
  Timer? _timer;
  bool _isRunning = false;
  bool _isCompleted = false;
  DateTime? _pausedAt;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _secondsRemaining = widget.durationSeconds;
    if (widget.autoStart) {
      _start();
    }
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _timer?.cancel();
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.paused) {
      if (_isRunning) {
        _pausedAt = DateTime.now();
      }
    } else if (state == AppLifecycleState.resumed) {
      if (_isRunning && _pausedAt != null) {
        final pausedDuration = DateTime.now().difference(_pausedAt!).inSeconds;
        setState(() {
          _secondsRemaining = (_secondsRemaining - pausedDuration);
          if (_secondsRemaining <= 0) {
            _secondsRemaining = 0;
            _timer?.cancel();
            _isRunning = false;
            _isCompleted = true;
            widget.onComplete?.call();
          }
        });
        _pausedAt = null;
      }
    }
  }

  void _start() {
    if (_isCompleted) return;

    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        if (_secondsRemaining > 0) {
          _secondsRemaining--;
        } else {
          _timer?.cancel();
          _isRunning = false;
          _isCompleted = true;
          widget.onComplete?.call();
        }
      });
    });
    setState(() => _isRunning = true);
  }

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

  void _reset() {
    _timer?.cancel();
    setState(() {
      _secondsRemaining = widget.durationSeconds;
      _isRunning = false;
      _isCompleted = false;
    });
  }

  void _skip() {
    _timer?.cancel();
    setState(() {
      _secondsRemaining = 0;
      _isRunning = false;
      _isCompleted = true;
    });
    widget.onComplete?.call();
  }

  String _formatTime() {
    final minutes = _secondsRemaining ~/ 60;
    final secs = _secondsRemaining % 60;
    return '${minutes.toString().padLeft(2, '0')}:${secs.toString().padLeft(2, '0')}';
  }

  Color _getTimerColor() {
    if (_isCompleted) return AppTheme.successColor;
    if (_secondsRemaining <= 10) return AppTheme.errorColor;
    if (_secondsRemaining <= 30) return Colors.orange;
    return AppTheme.primaryColor;
  }

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;
    final progress = widget.durationSeconds > 0
        ? _secondsRemaining / widget.durationSeconds
        : 0.0;

    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Stack(
          alignment: Alignment.center,
          children: [
            SizedBox(
              width: 200,
              height: 200,
              child: CircularProgressIndicator(
                value: progress,
                strokeWidth: 12,
                backgroundColor: AppTheme.xpBarBackground,
                color: _getTimerColor(),
              ),
            ),
            Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  _formatTime(),
                  style: Theme.of(context).textTheme.displayLarge?.copyWith(
                        fontSize: 48,
                        fontWeight: FontWeight.bold,
                        color: _getTimerColor(),
                        fontFamily: 'monospace',
                      ),
                ),
                if (_isCompleted)
                  Padding(
                    padding: const EdgeInsets.only(top: 8),
                    child: Text(
                      l10n.timerComplete,
                      style: const TextStyle(
                        color: AppTheme.successColor,
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                        letterSpacing: 1.5,
                      ),
                    ),
                  ),
              ],
            ),
          ],
        ),
        const SizedBox(height: 24),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            if (!_isCompleted) ...[
              ElevatedButton.icon(
                onPressed: _isRunning ? _pause : _start,
                icon: Icon(_isRunning ? Icons.pause : Icons.play_arrow),
                label: Text(_isRunning ? l10n.timerPause : 'START'),
                style: ElevatedButton.styleFrom(
                  backgroundColor:
                      _isRunning ? Colors.orange : AppTheme.primaryColor,
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(
                    horizontal: 24,
                    vertical: 12,
                  ),
                ),
              ),
              const SizedBox(width: 12),
              OutlinedButton.icon(
                onPressed: _reset,
                icon: const Icon(Icons.refresh),
                label: Text(l10n.timerReset),
                style: OutlinedButton.styleFrom(
                  foregroundColor: AppTheme.primaryColor,
                  side: const BorderSide(color: AppTheme.primaryColor),
                  padding: const EdgeInsets.symmetric(
                    horizontal: 24,
                    vertical: 12,
                  ),
                ),
              ),
              const SizedBox(width: 12),
              OutlinedButton.icon(
                onPressed: _skip,
                icon: const Icon(Icons.skip_next),
                label: Text(l10n.timerSkip),
                style: OutlinedButton.styleFrom(
                  foregroundColor: Colors.grey,
                  side: const BorderSide(color: Colors.grey),
                  padding: const EdgeInsets.symmetric(
                    horizontal: 24,
                    vertical: 12,
                  ),
                ),
              ),
            ] else ...[
              ElevatedButton.icon(
                onPressed: _reset,
                icon: const Icon(Icons.replay),
                label: Text(l10n.timerRestart),
                style: ElevatedButton.styleFrom(
                  backgroundColor: AppTheme.primaryColor,
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(
                    horizontal: 32,
                    vertical: 12,
                  ),
                ),
              ),
            ],
          ],
        ),
      ],
    );
  }
}
