import 'dart:async';

import 'package:flutter/material.dart';

import '../../core/contracts/library.dart';
import '../../shared/utils/format_utils.dart';
import 'emby_detail_helpers.dart';
import 'widgets/hero_action_buttons.dart';
import 'widgets/stream_selector_actions.dart';

Widget buildEmbyHeroActions({
  required EmbyRawItem displayItem,
  required bool canPlay,
  required List<EmbyRawMediaSource> sortedSources,
  required List<EmbyRawMediaStream> subtitles,
  required List<EmbyRawMediaStream> audios,
  required int? effectiveSubtitleIdx,
  required bool compact,
  required int selectedSourceIdx,
  required int? selectedSubtitleIdx,
  required int selectedAudioIdx,
  required bool isPlayed,
  required bool isFavorite,
  required bool isLaunchingPlayer,
  required ValueChanged<int> onSelectSource,
  required ValueChanged<int?> onSelectSubtitle,
  required ValueChanged<int> onSelectAudio,
  required VoidCallback onTogglePlayed,
  required VoidCallback onToggleFavorite,
  required VoidCallback onPlay,
  required VoidCallback onReplay,
}) {
  final btnH = compact ? 44.0 : 52.0;
  final progressPercent = detailProgressPercent(displayItem);
  final hasProgress = progressPercent != null && progressPercent > 0;
  final pos = displayItem.UserData?.PlaybackPositionTicks;
  final positionClock = pos != null && pos > 0 ? formatTicksAsClock(pos) : null;

  final extraActions = buildStreamSelectorPills(
    subtitles: subtitles,
    audios: audios,
    selectedSubtitleIdx: selectedSubtitleIdx,
    selectedAudioIdx: selectedAudioIdx,
    onSelectSubtitle: onSelectSubtitle,
    onSelectAudio: onSelectAudio,
    height: btnH,
  );

  if (sortedSources.length > 1) {
    extraActions.add(
      HeroPillDropdownButton(
        height: btnH,
        icon: Icons.video_file_outlined,
        menuChildren: buildVersionMenuButtons(
          sources: sortedSources,
          selectedSourceIdx: selectedSourceIdx,
          onSelectSource: onSelectSource,
        ),
      ),
    );
  }

  return DetailHeroActions(
    showReplay: hasProgress && canPlay,
    onReplay: canPlay ? () => unawaited(Future<void>.sync(onReplay)) : null,
    isPlayed: isPlayed,
    onTogglePlayed: () => unawaited(Future<void>.sync(onTogglePlayed)),
    isFavorite: isFavorite,
    onToggleFavorite: () => unawaited(Future<void>.sync(onToggleFavorite)),
    extraIconActions: extraActions,
    onPlay: canPlay ? () => unawaited(Future<void>.sync(onPlay)) : null,
    playLabel: hasProgress ? '继续播放' : '播放',
    progressPercent: progressPercent,
    trailingLabel: positionClock,
    isPlayLoading: isLaunchingPlayer,
    compact: compact,
  );
}
