import 'package:flutter/material.dart';

import '../l10n/generated/app_localizations.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LinkTrustService extends ChangeNotifier {
  static LinkTrustService? _instance;
  final Set<String> _trusted = {};
  bool _loaded = false;

  static LinkTrustService get instance {
    _instance ??= LinkTrustService._();
    return _instance!;
  }

  LinkTrustService._() {
    _load();
  }

  Future<void> _load() async {
    if (_loaded) return;
    _loaded = true;
    final prefs = await SharedPreferences.getInstance();
    final domains = prefs.getStringList('trusted_domains') ?? [];
    _trusted.addAll(domains);
    notifyListeners();
  }

  bool isTrusted(String host) {
    host = host.toLowerCase();
    for (final pattern in _trusted) {
      if (_matches(host, pattern)) return true;
    }
    return false;
  }

  Future<void> addTrustedDomain(String host) async {
    host = host.toLowerCase();
    _trusted.add(host);
    notifyListeners();
    final prefs = await SharedPreferences.getInstance();
    await prefs.setStringList('trusted_domains', _trusted.toList());
  }

  bool _matches(String host, String pattern) {
    if (pattern.startsWith('*.')) {
      final suffix = pattern.substring(2);
      return host == suffix || host.endsWith('.$suffix');
    }
    return host == pattern;
  }
}

Future<bool?> showLinkTrustDialog(BuildContext context, String domain) async {
  bool remember = false;
  return showDialog<bool>(
    context: context,
    builder: (ctx) => StatefulBuilder(
      builder: (ctx, setDialogState) {
        final l10n = AppL10n.of(ctx);
        return AlertDialog(
          title: Text(l10n.linkTrustTitle),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(l10n.linkTrustBody(domain)),
              const SizedBox(height: 12),
              Row(
                children: [
                  SizedBox(
                    width: 24,
                    height: 24,
                    child: Checkbox(
                      value: remember,
                      onChanged: (v) =>
                          setDialogState(() => remember = v ?? false),
                    ),
                  ),
                  const SizedBox(width: 8),
                  Flexible(child: Text(l10n.linkTrustRememberDomain)),
                ],
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(ctx).pop(null),
              child: Text(l10n.cancelAction),
            ),
            TextButton(
              onPressed: () => Navigator.of(ctx).pop(remember),
              child: Text(l10n.openAction),
            ),
          ],
        );
      },
    ),
  );
}
