import 'package:audioplayers/audioplayers.dart';
import 'package:english_learning/features/learning/modules/material/widgets/loading/media_loading_widget.dart';
import 'package:flutter/material.dart';

class AudioPlayerWidget extends StatefulWidget {
  final String audioFileName;
  final String? baseUrl;

  const AudioPlayerWidget({
    super.key,
    required this.audioFileName,
    this.baseUrl,
  });

  @override
  State<AudioPlayerWidget> createState() => AudioPlayerWidgetState();
}

class AudioPlayerWidgetState extends State<AudioPlayerWidget>
    with TickerProviderStateMixin {
  late AudioPlayer _audioPlayer;
  late AnimationController _loadingController;
  late AnimationController _fadeController;

  PlayerState _playerState = PlayerState.stopped;
  Duration _duration = Duration.zero;
  Duration _position = Duration.zero;
  bool _isAudioLoaded = false;
  String? _errorMessage;
  double _volume = 1.0;
  bool _isDisposed = false;

  @override
  void initState() {
    super.initState();
    _audioPlayer = AudioPlayer();
    _loadingController = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 1),
    )..repeat();

    _fadeController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 300),
    );

    _setupAudioPlayer();
  }

  void _setupAudioPlayer() {
    if (widget.audioFileName.isNotEmpty) {
      String fullAudioUrl = _getFullAudioUrl();

      _audioPlayer.setSource(UrlSource(fullAudioUrl)).then((_) {
        if (!_isDisposed) {
          setState(() {
            _isAudioLoaded = true;
            _fadeController.forward();
          });
        }
      }).catchError((error) {
        if (!_isDisposed) {
          setState(() {
            _errorMessage = "Failed to load audio: $error";
          });
        }
      });

      _setupAudioListeners();
    }
  }

  void _setupAudioListeners() {
    _audioPlayer.onPlayerStateChanged.listen((state) {
      if (!_isDisposed) {
        setState(() => _playerState = state);
      }
    });

    _audioPlayer.onDurationChanged.listen((newDuration) {
      if (!_isDisposed) {
        setState(() => _duration = newDuration);
      }
    });

    _audioPlayer.onPositionChanged.listen((newPosition) {
      if (!_isDisposed) {
        setState(() => _position = newPosition);
      }
    });
  }

  String _getFullAudioUrl() {
    return widget.audioFileName.startsWith('http')
        ? widget.audioFileName
        : '${widget.baseUrl ?? ''}${widget.audioFileName}';
  }

  Widget _buildErrorWidget() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.grey[100],
        borderRadius: BorderRadius.circular(16),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(
            Icons.error_outline,
            color: Colors.red[400],
            size: 32,
          ),
          const SizedBox(height: 8),
          Text(
            _errorMessage ?? 'Error loading audio',
            style: TextStyle(
              color: Colors.red[400],
              fontSize: 14,
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 12),
          TextButton.icon(
            onPressed: () {
              setState(() {
                _errorMessage = null;
                _isAudioLoaded = false;
                _setupAudioPlayer();
              });
            },
            icon: const Icon(Icons.refresh),
            label: const Text('Retry'),
            style: TextButton.styleFrom(
              foregroundColor: Colors.blue,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildAudioControls() {
    return FadeTransition(
      opacity: _fadeController,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 8,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Row(
              children: [
                _buildPlayButton(),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      _buildTimelineIndicator(),
                      const SizedBox(height: 4),
                      _buildProgressSlider(),
                    ],
                  ),
                ),
                const SizedBox(width: 12),
                _buildVolumeButton(),
              ],
            ),
            if (_errorMessage != null)
              Padding(
                padding: const EdgeInsets.only(top: 8),
                child: Text(
                  _errorMessage!,
                  style: TextStyle(
                    color: Colors.red[400],
                    fontSize: 12,
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildPlayButton() {
    return IconButton(
      icon: Icon(
        _playerState == PlayerState.playing
            ? Icons.pause_rounded
            : Icons.play_arrow_rounded,
        color: Colors.blue,
        size: 32,
      ),
      onPressed: _isAudioLoaded
          ? () {
              if (_playerState == PlayerState.playing) {
                _audioPlayer.pause();
              } else {
                _audioPlayer.resume();
              }
            }
          : null,
    );
  }

  Widget _buildTimelineIndicator() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          _formatDuration(_position),
          style: const TextStyle(fontSize: 12),
        ),
        Text(
          _formatDuration(_duration),
          style: const TextStyle(fontSize: 12),
        ),
      ],
    );
  }

  Widget _buildProgressSlider() {
    return SliderTheme(
      data: const SliderThemeData(
        trackHeight: 4,
        thumbShape: RoundSliderThumbShape(enabledThumbRadius: 6),
        overlayShape: RoundSliderOverlayShape(overlayRadius: 14),
      ),
      child: Slider(
        value: _position.inSeconds.toDouble(),
        min: 0.0,
        max: _duration.inSeconds.toDouble(),
        onChanged: _isAudioLoaded
            ? (value) {
                final position = Duration(seconds: value.toInt());
                _audioPlayer.seek(position);
              }
            : null,
        activeColor: Colors.blue,
        inactiveColor: Colors.grey[300],
      ),
    );
  }

  Widget _buildVolumeButton() {
    return IconButton(
      icon: Icon(
        _volume == 0.0 ? Icons.volume_off : Icons.volume_up,
        color: _volume == 0.0 ? Colors.grey : Colors.blue,
        size: 24,
      ),
      onPressed: _isAudioLoaded
          ? () {
              if (_volume == 0.0) {
                _audioPlayer.setVolume(1.0);
                setState(() => _volume = 1.0);
              } else {
                _audioPlayer.setVolume(0.0);
                setState(() => _volume = 0.0);
              }
            }
          : null,
    );
  }

  @override
  Widget build(BuildContext context) {
    if (_errorMessage != null) {
      return _buildErrorWidget();
    }

    if (!_isAudioLoaded) {
      return const AudioShimmerLoader();
    }

    return _buildAudioControls();
  }

  String _formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, "0");
    String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
    String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
    return "$twoDigitMinutes:$twoDigitSeconds";
  }

  void stopAndResetAudio() {
    _audioPlayer.stop();
    _audioPlayer.seek(Duration.zero);
  }

  @override
  void dispose() {
    _isDisposed = true;
    _audioPlayer.dispose();
    _loadingController.dispose();
    _fadeController.dispose();
    super.dispose();
  }
}
