import '../l10n/generated/app_localizations.dart';
import '../src/rust/api.dart' as rust;
import 'talk_power_warning.dart';

class VoiceStatusSummary {
  const VoiceStatusSummary({
    required this.modeLabel,
    required this.line1,
    required this.line2,
    required this.statusText,
    required this.micOn,
    required this.talkPowerBlocked,
    required this.muted,
  });

  final String modeLabel;
  final String line1;
  final String line2;
  final String statusText;
  final bool micOn;
  final bool talkPowerBlocked;
  final bool muted;
}

String voiceModeLabel(AppL10n l10n, rust.BridgeTransmitMode transmitMode) {
  switch (transmitMode) {
    case rust.BridgeTransmitMode.ptt:
      return l10n.voiceModePtt;
    case rust.BridgeTransmitMode.continuous:
      return l10n.voiceModeContinuous;
    case rust.BridgeTransmitMode.voiceActivity:
      return l10n.voiceModeVoiceActivity;
  }
}

VoiceStatusSummary voiceStatusSummary({
  required AppL10n l10n,
  required rust.BridgeTransmitMode transmitMode,
  required int releaseTailMs,
  required String pttBoundKeyLabel,
  required bool isTouchOnly,
  required bool inputMuted,
  required bool outputMuted,
  required bool pttActive,
  int? talkPower,
  int? neededTalkPower,
  bool? talkPowerGranted,
}) {
  final modeLabel = voiceModeLabel(l10n, transmitMode);
  final talkPowerBlocked = isTalkPowerBlocked(
    talkPower: talkPower,
    neededTalkPower: neededTalkPower,
    talkPowerGranted: talkPowerGranted,
  );
  final micOn = inputMuted || outputMuted || talkPowerBlocked
      ? false
      : switch (transmitMode) {
          rust.BridgeTransmitMode.continuous => true,
          _ => pttActive,
        };

  final line1 = transmitMode == rust.BridgeTransmitMode.ptt
      ? isTouchOnly
            ? '$modeLabel \u00b7 ${l10n.voicePttHoldHint}'
            : '$modeLabel \u00b7 ${pttBoundKeyLabel.isEmpty ? "\u2014" : pttBoundKeyLabel}'
      : modeLabel;
  final tailText = transmitMode == rust.BridgeTransmitMode.ptt
      ? '$releaseTailMs${l10n.voiceReleaseTailHint} ${l10n.voiceReleaseTailLabel.toLowerCase()}'
      : null;
  final statusText = talkPowerBlocked
      ? 'Insufficient permission'
      : inputMuted
      ? '${l10n.voiceMicOff} (muted)'
      : outputMuted
      ? 'Speaker muted'
      : micOn
      ? l10n.voiceMicOn
      : l10n.voiceMicOff;

  return VoiceStatusSummary(
    modeLabel: modeLabel,
    line1: line1,
    line2: tailText == null ? statusText : '$tailText \u00b7 $statusText',
    statusText: statusText,
    micOn: micOn,
    talkPowerBlocked: talkPowerBlocked,
    muted: inputMuted || outputMuted,
  );
}
