import 'dart:io';

import 'package:didvan/config/theme_data.dart';
import 'package:didvan/constants/app_icons.dart';
import 'package:didvan/services/media/media.dart';
import 'package:didvan/views/home/widgets/audio/audio_slider.dart';
import 'package:didvan/views/widgets/didvan/icon_button.dart';
import 'package:flutter/material.dart';

class AudioWidget extends StatelessWidget {
  final String? audioUrl;
  final File? audioFile;
  final int id;
  const AudioWidget({
    Key? key,
    this.audioUrl,
    this.audioFile,
    required this.id,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<bool>(
      stream: MediaService.audioPlayer.playingStream,
      builder: (context, snapshot) {
        return Row(
          children: [
            Expanded(
              child: AudioSlider(
                tag: 'message-$id',
              ),
            ),
            _AudioControllerButton(
              audioFile: audioFile,
              audioUrl: audioUrl,
              id: id,
            ),
          ],
        );
      },
    );
  }
}

class _AudioControllerButton extends StatelessWidget {
  final String? audioUrl;
  final File? audioFile;
  final int id;

  const _AudioControllerButton(
      {Key? key, this.audioUrl, this.audioFile, required this.id})
      : super(key: key);

  bool get _nowPlaying => MediaService.audioPlayerTag == 'message-$id';

  @override
  Widget build(BuildContext context) {
    return DidvanIconButton(
      icon: MediaService.audioPlayer.playing == true && _nowPlaying
          ? DidvanIcons.pause_circle_solid
          : DidvanIcons.play_circle_solid,
      color: Theme.of(context).colorScheme.focusedBorder,
      onPressed: () {
        MediaService.handleAudioPlayback(
          audioSource: audioFile?.path ?? audioUrl,
          id: id,
          isNetworkAudio: audioFile == null,
          isVoiceMessage: true,
        );
      },
    );
  }
}
