import 'dart:io';

import 'package:didvan/config/theme_data.dart';
import 'package:didvan/constants/app_icons.dart';
import 'package:didvan/models/requests/studio.dart';
import 'package:didvan/models/studio_details_data.dart';
import 'package:didvan/services/media/media.dart';
import 'package:didvan/views/widgets/audio/audio_slider.dart';
import 'package:didvan/views/podcasts/studio_details/studio_details_state.dart';
import 'package:didvan/views/widgets/didvan/icon_button.dart';
import 'package:flutter/material.dart';
import 'package:just_audio/just_audio.dart';
import 'package:provider/provider.dart';

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

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<bool>(
      stream: MediaService.audioPlayer.playingStream,
      builder: (context, snapshot) {
        return Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              child: Padding(
                padding: const EdgeInsets.only(top: 12),
                child: Row(
                  children: [
                    Expanded(
                      child: AudioSlider(
                        tag: audioMetaData != null
                            ? '${audioMetaData!.type}-$id'
                            : 'message-$id',
                        duration:
                            audioMetaData?.duration ?? duration?.inSeconds,
                        showTimer: true,
                      ),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(width: 12),
            _AudioControllerButton(
              audioFile: audioFile,
              audioUrl: audioUrl,
              id: id,
              audioMetaData: audioMetaData,
            ),
          ],
        );
      },
    );
  }
}

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

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

  bool get _nowPlaying =>
      MediaService.audioPlayerTag ==
      (audioMetaData != null ? '${audioMetaData!.type}-$id' : 'message-$id');

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<PlayerState>(
        stream: MediaService.audioPlayer.playerStateStream,
        builder: (context, snapshot) {
          if (snapshot.hasData &&
              snapshot.data!.processingState == ProcessingState.completed) {
            MediaService.audioPlayer.pause();
            MediaService.audioPlayer.seek(Duration.zero);
          }
          return DidvanIconButton(
            icon: MediaService.audioPlayer.playing && _nowPlaying
                ? DidvanIcons.pause_circle_solid
                : DidvanIcons.play_circle_solid,
            gestureSize: 36,
            color: Theme.of(context).colorScheme.focusedBorder,
            onPressed: () async {
              if (audioMetaData?.type == 'podcast') {
                final state = context.read<StudioDetailsState>();
                if (MediaService.currentPodcast == null) {
                  await state.getStudioDetails(
                    id,
                    args: const StudioRequestArgs(page: 0, type: 'podcast'),
                  );
                }
              }
              if (snapshot.data == null &&
                  _nowPlaying &&
                  MediaService.audioPlayer.playing) {
                return;
              }
              if (audioMetaData != null) {
                MediaService.currentPodcast = audioMetaData;
              }
              MediaService.handleAudioPlayback(
                audioSource: audioFile?.path ?? audioUrl,
                id: id,
                isNetworkAudio: audioFile == null,
                isVoiceMessage: audioMetaData == null,
              );
            },
          );
        });
  }
}
