part of '../settings_modal.dart';

class _NotificationsSection extends ConsumerWidget {
  final PyramidTheme pt;
  const _NotificationsSection({required this.pt});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final desktop = ref.watch(notifDesktopProvider);
    final sound = ref.watch(notifSoundProvider);
    final preview = ref.watch(notifPreviewProvider);
    final dmMentionOnly = ref.watch(notifMentionOnlyDmProvider);

    return SingleChildScrollView(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _SectionTitle(
              title: 'Benachrichtigungen',
              subtitle: 'Bestimme, wann und wie du benachrichtigt wirst.',
              pt: pt),
          _SettingsGroup(title: 'Desktop', pt: pt, children: [
            _SettingsRow(
              title: 'Desktop-Benachrichtigungen',
              desc: 'Zeige Systembenachrichtigungen bei neuen Nachrichten',
              pt: pt,
              control: _Toggle(
                value: desktop,
                pt: pt,
                onChanged: (v) => ref.read(notifDesktopProvider.notifier).set(v),
              ),
            ),
            _Divider(pt: pt),
            _SettingsRow(
              title: 'Benachrichtigungston',
              desc: 'Sound abspielen wenn eine Nachricht eingeht',
              pt: pt,
              control: _Toggle(
                value: sound,
                pt: pt,
                onChanged: (v) => ref.read(notifSoundProvider.notifier).set(v),
              ),
            ),
            _Divider(pt: pt),
            _SettingsRow(
              title: 'Nachrichtenvorschau',
              desc: 'Nachrichteninhalt in Benachrichtigung anzeigen',
              pt: pt,
              control: _Toggle(
                value: preview,
                pt: pt,
                onChanged: (v) => ref.read(notifPreviewProvider.notifier).set(v),
              ),
            ),
          ]),
          const SizedBox(height: 20),
          _SettingsGroup(title: 'Filter', pt: pt, children: [
            _SettingsRow(
              title: 'Nur Erwähnungen (DMs)',
              desc: 'Benachrichtigung nur bei direkten @Erwähnungen',
              pt: pt,
              control: _Toggle(
                value: dmMentionOnly,
                pt: pt,
                onChanged: (v) => ref.read(notifMentionOnlyDmProvider.notifier).set(v),
              ),
            ),
          ]),
          const SizedBox(height: 20),
          Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: pt.bg2,
              borderRadius: BorderRadius.circular(10),
              border: Border.all(color: pt.border),
            ),
            child: Row(
              children: [
                Icon(Icons.info_outline_rounded, size: 16, color: pt.fgDim),
                const SizedBox(width: 10),
                Expanded(
                  child: Text(
                    'Push-Benachrichtigungen für Android/iOS sind in Vorbereitung.',
                    style: TextStyle(color: pt.fgMuted, fontSize: 12),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

class _NotificationsSettingsGroup extends ConsumerStatefulWidget {
  final PyramidTheme pt;
  const _NotificationsSettingsGroup({required this.pt});
  @override
  ConsumerState<_NotificationsSettingsGroup> createState() =>
      _NotificationsSettingsGroupState();
}

class _NotificationsSettingsGroupState
    extends ConsumerState<_NotificationsSettingsGroup> {
  bool _running = false;
  String? _result;
  bool _retryRunning = false;
  String? _retryResult;

  Future<void> _runDiag() async {
    setState(() { _running = true; _result = null; });
    final client = await ref.read(matrixClientProvider.future);
    final diag = await fcmDiagnostics(client);
    if (mounted) setState(() { _running = false; _result = diag; });
  }

  Future<void> _runRetry() async {
    setState(() { _retryRunning = true; _retryResult = null; });
    final client = await ref.read(matrixClientProvider.future);
    final result = await retryPusherRegistration(client);
    if (mounted) setState(() { _retryRunning = false; _retryResult = result; });
  }

  @override
  Widget build(BuildContext context) {
    final pt = widget.pt;
    if (!Platform.isAndroid) return const SizedBox.shrink();
    return _SettingsGroup(title: 'Push-Benachrichtigungen', pt: pt, children: [
      _SettingsRow(
        title: 'Akku-Optimierung deaktivieren',
        desc: 'Samsung / andere OEMs unterdrücken sonst Benachrichtigungen bei geschlossener App.',
        pt: pt,
        showArrow: true,
        onTap: openBatteryOptimizationSettings,
        control: Icon(Icons.battery_saver_outlined, size: 16, color: pt.fgDim),
      ),
      _Divider(pt: pt),
      _SettingsRow(
        title: 'FCM Diagnose',
        desc: _result ?? 'Prüft ob FCM-Token & Pusher korrekt registriert sind.',
        pt: pt,
        onTap: _running ? null : _runDiag,
        control: _running
            ? SizedBox(
                width: 16,
                height: 16,
                child: CircularProgressIndicator(strokeWidth: 2, color: pt.accent),
              )
            : Icon(Icons.bug_report_outlined, size: 16, color: pt.fgDim),
      ),
      _Divider(pt: pt),
      _SettingsRow(
        title: 'Pusher neu registrieren',
        desc: _retryResult ?? 'Pusher beim Homeserver erneut anmelden.',
        pt: pt,
        onTap: _retryRunning ? null : _runRetry,
        control: _retryRunning
            ? SizedBox(
                width: 16,
                height: 16,
                child: CircularProgressIndicator(strokeWidth: 2, color: pt.accent),
              )
            : Icon(Icons.sync_outlined, size: 16, color: pt.fgDim),
      ),
    ]);
  }
}
