import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:it0_app/l10n/app_localizations.dart';
import '../../data/notification_channel.dart';
import '../../../../core/network/dio_client.dart';

// ── Providers ──────────────────────────────────────────────────────────────

final _channelPrefsProvider = FutureProvider.autoDispose<List<NotificationChannelPreference>>((ref) async {
  final dio = ref.watch(dioClientProvider);
  final res = await dio.get('/api/v1/notifications/channels/me/preferences');
  final list = res.data as List;
  return list
      .map((e) => NotificationChannelPreference.fromJson(e as Map<String, dynamic>))
      .toList();
});

// ── Page ───────────────────────────────────────────────────────────────────

class NotificationPreferencesPage extends ConsumerStatefulWidget {
  const NotificationPreferencesPage({super.key});

  @override
  ConsumerState<NotificationPreferencesPage> createState() => _NotificationPreferencesPageState();
}

class _NotificationPreferencesPageState extends ConsumerState<NotificationPreferencesPage> {
  final Map<String, bool> _pendingChanges = {};
  bool _saving = false;

  Future<void> _saveChanges() async {
    if (_pendingChanges.isEmpty) return;
    setState(() => _saving = true);
    try {
      final dio = ref.read(dioClientProvider);
      final preferences = _pendingChanges.entries
          .map((e) => {'channelKey': e.key, 'enabled': e.value})
          .toList();
      await dio.put(
        '/api/v1/notifications/channels/me/preferences',
        data: {'preferences': preferences},
      );
      _pendingChanges.clear();
      ref.invalidate(_channelPrefsProvider);
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(AppLocalizations.of(context).preferencesSavedMessage), duration: const Duration(seconds: 2)),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('保存失败: $e'), backgroundColor: Colors.red),
        );
      }
    } finally {
      if (mounted) setState(() => _saving = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    final prefsAsync = ref.watch(_channelPrefsProvider);
    final theme = Theme.of(context);

    return Scaffold(
      appBar: AppBar(
        title: Text(AppLocalizations.of(context).notificationPreferencesTitle),
        actions: [
          if (_pendingChanges.isNotEmpty)
            TextButton(
              onPressed: _saving ? null : _saveChanges,
              child: _saving
                  ? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2))
                  : Text(AppLocalizations.of(context).saveButton),
            ),
        ],
      ),
      body: prefsAsync.when(
        loading: () => const Center(child: CircularProgressIndicator()),
        error: (e, _) => Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(AppLocalizations.of(context).notificationLoadingFailed, style: theme.textTheme.titleMedium),
              const SizedBox(height: 8),
              TextButton(
                onPressed: () => ref.invalidate(_channelPrefsProvider),
                child: Text(AppLocalizations.of(context).retryButton),
              ),
            ],
          ),
        ),
        data: (prefs) {
          if (prefs.isEmpty) {
            return Center(child: Text(AppLocalizations.of(context).noNotificationChannels));
          }

          final mandatory = prefs.where((p) => p.isMandatory).toList();
          final optional = prefs.where((p) => !p.isMandatory).toList();

          return ListView(
            children: [
              // Info banner
              Container(
                margin: const EdgeInsets.all(16),
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: theme.colorScheme.primaryContainer.withOpacity(0.3),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Row(
                  children: [
                    Icon(Icons.info_outline, size: 16, color: theme.colorScheme.primary),
                    const SizedBox(width: 8),
                    Expanded(
                      child: Text(
                        AppLocalizations.of(context).notificationPreferencesInfo,
                        style: theme.textTheme.bodySmall?.copyWith(
                          color: theme.colorScheme.onSurface.withOpacity(0.7),
                        ),
                      ),
                    ),
                  ],
                ),
              ),

              // Mandatory channels
              if (mandatory.isNotEmpty) ...[
                Padding(
                  padding: const EdgeInsets.fromLTRB(16, 8, 16, 4),
                  child: Text(
                    AppLocalizations.of(context).mandatoryNotificationsSection,
                    style: theme.textTheme.labelSmall?.copyWith(
                      color: theme.colorScheme.onSurface.withOpacity(0.5),
                      letterSpacing: 0.5,
                    ),
                  ),
                ),
                ...mandatory.map((pref) => _ChannelTile(
                  pref: pref,
                  currentValue: _pendingChanges[pref.channelKey] ?? pref.enabled,
                  onChanged: null, // mandatory — disabled
                )),
              ],

              // Optional channels
              if (optional.isNotEmpty) ...[
                Padding(
                  padding: const EdgeInsets.fromLTRB(16, 16, 16, 4),
                  child: Text(
                    AppLocalizations.of(context).optionalNotificationsSection,
                    style: theme.textTheme.labelSmall?.copyWith(
                      color: theme.colorScheme.onSurface.withOpacity(0.5),
                      letterSpacing: 0.5,
                    ),
                  ),
                ),
                ...optional.map((pref) => _ChannelTile(
                  pref: pref,
                  currentValue: _pendingChanges[pref.channelKey] ?? pref.enabled,
                  onChanged: (val) {
                    setState(() {
                      _pendingChanges[pref.channelKey] = val;
                    });
                  },
                )),
              ],

              const SizedBox(height: 32),

              // Save button at bottom
              if (_pendingChanges.isNotEmpty)
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 16),
                  child: FilledButton(
                    onPressed: _saving ? null : _saveChanges,
                    child: _saving
                        ? const SizedBox(
                            width: 20, height: 20,
                            child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white),
                          )
                        : Text(AppLocalizations.of(context).savePreferencesButton),
                  ),
                ),
            ],
          );
        },
      ),
    );
  }
}

class _ChannelTile extends StatelessWidget {
  final NotificationChannelPreference pref;
  final bool currentValue;
  final ValueChanged<bool>? onChanged;

  const _ChannelTile({
    required this.pref,
    required this.currentValue,
    required this.onChanged,
  });

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    return SwitchListTile(
      title: Row(
        children: [
          Text(pref.channelName),
          if (pref.isMandatory) ...[
            const SizedBox(width: 6),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
              decoration: BoxDecoration(
                color: Colors.amber.shade100,
                borderRadius: BorderRadius.circular(4),
              ),
              child: Text(
                AppLocalizations.of(context).requiredLabel,
                style: theme.textTheme.labelSmall?.copyWith(
                  color: Colors.amber.shade800,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ],
        ],
      ),
      subtitle: Text(
        pref.channelKey,
        style: theme.textTheme.bodySmall?.copyWith(
          color: theme.colorScheme.onSurface.withOpacity(0.4),
          fontFamily: 'monospace',
        ),
      ),
      value: currentValue,
      onChanged: onChanged,
    );
  }
}
