import 'dart:async';

import 'package:flutter/material.dart';

import '../../../core/infra/player_engine/player_engine.dart';

class PlayerPlayPauseButton extends StatefulWidget {
  final PlayerEngine player;


  final double? iconSize;


  final BoxConstraints? constraints;

  const PlayerPlayPauseButton({
    super.key,
    required this.player,
    this.iconSize,
    this.constraints,
  });

  @override
  State<PlayerPlayPauseButton> createState() => _PlayerPlayPauseButtonState();
}

class _PlayerPlayPauseButtonState extends State<PlayerPlayPauseButton> {
  late bool _playing;
  StreamSubscription<bool>? _sub;

  @override
  void initState() {
    super.initState();
    _playing = widget.player.state.playing;
    _sub = widget.player.stream.playing.listen((playing) {
      if (mounted) setState(() => _playing = playing);
    });
  }

  @override
  void didUpdateWidget(covariant PlayerPlayPauseButton oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.player != widget.player) {
      unawaited(_sub?.cancel());
      _playing = widget.player.state.playing;
      _sub = widget.player.stream.playing.listen((playing) {
        if (mounted) setState(() => _playing = playing);
      });
    }
  }

  @override
  void dispose() {
    unawaited(_sub?.cancel());
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return IconButton(
      tooltip: _playing ? '暂停' : '播放',
      constraints: widget.constraints,
      padding: widget.constraints != null ? EdgeInsets.zero : null,
      onPressed: () {
        if (_playing) {
          unawaited(widget.player.pause());
        } else {
          unawaited(widget.player.play());
        }
      },
      icon: Icon(
        _playing ? Icons.pause : Icons.play_arrow,
        color: Colors.white,
        size: widget.iconSize ?? 30,
      ),
    );
  }
}
