import 'package:audioplayers/audioplayers.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> {
  late AudioPlayer _audioPlayer;
  PlayerState _playerState = PlayerState.stopped;
  Duration _duration = Duration.zero;
  Duration _position = Duration.zero;
  bool _isAudioLoaded = false;
  String? _errorMessage;
  double _volume = 1.0;

  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    _audioPlayer = AudioPlayer();
    _setupAudioPlayer();
  }

  void _setupAudioPlayer() {
    if (widget.audioFileName.isNotEmpty) {
      String fullAudioUrl = widget.audioFileName.startsWith('http')
          ? widget.audioFileName
          : '${widget.baseUrl ?? ''}${widget.audioFileName}';

      _audioPlayer.setSource(UrlSource(fullAudioUrl)).then((_) {
        setState(() {
          _isAudioLoaded = true;
        });
      }).catchError((error) {
        setState(() {
          _errorMessage = "Failed to load audio";
        });
      });

      _audioPlayer.onPlayerStateChanged.listen((state) {
        setState(() {
          _playerState = state;
        });
      });

      _audioPlayer.onDurationChanged.listen((newDuration) {
        setState(() {
          _duration = newDuration;
        });
      });

      _audioPlayer.onPositionChanged.listen((newPosition) {
        setState(() {
          _position = newPosition;
        });
      });
    }
  }

  @override
  void dispose() {
    _audioPlayer.stop();
    _audioPlayer.dispose();
    super.dispose();
  }

  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
  Widget build(BuildContext context) {
    if (_errorMessage != null) {
      return Text(
        _errorMessage!,
        style: const TextStyle(
          color: Colors.red,
        ),
      );
    }

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

    return 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: Row(
        children: [
          // Play/Pause Button
          IconButton(
            icon: Icon(
              _playerState == PlayerState.playing
                  ? Icons.pause
                  : Icons.play_arrow,
              color: Colors.blue,
              size: 32,
            ),
            onPressed: () {
              if (_playerState == PlayerState.playing) {
                _audioPlayer.pause();
              } else {
                _audioPlayer.resume();
              }
            },
          ),
          const SizedBox(width: 12),
          // Timeline and Slider
          Expanded(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // Timeline
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      _formatDuration(_position),
                      style: const TextStyle(
                        fontSize: 12,
                      ),
                    ),
                    Text(
                      _formatDuration(_duration),
                      style: const TextStyle(
                        fontSize: 12,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 4),
                // Slider
                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: (value) {
                      final position = Duration(seconds: value.toInt());
                      _audioPlayer.seek(position);
                    },
                    activeColor: Colors.blue,
                    inactiveColor: Colors.grey,
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(width: 12),
          // Mute Button
          IconButton(
            icon: Icon(
              Icons.volume_up,
              color: _volume == 0.0 ? Colors.grey : Colors.blue,
              size: 32,
            ),
            onPressed: () {
              if (_volume == 0.0) {
                _audioPlayer.setVolume(1.0);
                setState(() {
                  _volume = 1.0;
                });
              } else {
                _audioPlayer.setVolume(0.0);
                setState(() {
                  _volume = 0.0;
                });
              }
            },
          ),
        ],
      ),
    );
  }
}
