import 'package:flutter/material.dart';
import 'api_service.dart';
import 'auth_service.dart';

class AppProvider extends ChangeNotifier {
  final ApiService api = ApiService();
  late final AuthService auth;

  bool _loading = true;
  bool get loading => _loading;

  AppProvider() {
    auth = AuthService(api);
  }

  Future<void> init() async {
    await auth.init();
    
    // ignore: avoid_print
    print('[REASONABLE DOUBT-APP] Token status: access=${api.currentToken != null}, refresh=${api.currentRefresh != null}');
    
    // Proactively refresh token on startup if we have one
    // This ensures a fresh access token after app restart
    if (api.currentRefresh != null) {
      // ignore: avoid_print
      print('[REASONABLE DOUBT-APP] Attempting proactive token refresh...');
      try {
        await api.refreshAccessToken();
        // Save the new token to prefs
        final newToken = api.currentToken;
        if (newToken != null) {
          await auth.updateLocalToken(newToken);
          // ignore: avoid_print
          print('[REASONABLE DOUBT-APP] Token refresh successful');
        }
      } catch (e) {
        // ignore: avoid_print
        print('[REASONABLE DOUBT-APP] Token refresh failed: $e');
        // Token might be expired - user needs to re-login
      }
    } else {
      // ignore: avoid_print
      print('[REASONABLE DOUBT-APP] No refresh token - user not logged in');
    }
    
    _loading = false;
    notifyListeners();
  }

  // ═══════════════ CONVERSATIONS ═══════════════
  List<Map<String, dynamic>> conversations = [];
  String? activeConversationId;

  Future<void> loadConversations() async {
    try {
      final res = await api.getConversations();
      conversations = List<Map<String, dynamic>>.from(res['results'] ?? []);
      notifyListeners();
    } catch (_) {}
  }

  Future<String> createConversation({String? title, String? country, String? legalArea}) async {
    final effectiveCountry = country ?? auth.userCountry;
    final res = await api.createConversation(title: title, country: effectiveCountry, legalArea: legalArea);
    final id = res['id'].toString();
    conversations.insert(0, res);
    activeConversationId = id;
    notifyListeners();
    return id;
  }

  Future<void> deleteConversation(String id) async {
    await api.deleteConversation(id);
    conversations.removeWhere((c) => c['id']?.toString() == id);
    notifyListeners();
  }

  // ═══════════════ RIGHTS CARDS ═══════════════
  List<Map<String, dynamic>> rightsCards = [];
  bool rightsLoading = false;

  Future<void> loadRightsCards() async {
    rightsLoading = true;
    notifyListeners();
    try {
      final res = await api.getRightsCards();
      rightsCards = List<Map<String, dynamic>>.from(res['results'] ?? []);
    } catch (_) {}
    rightsLoading = false;
    notifyListeners();
  }

  // ═══════════════ COUNTRIES ═══════════════
  List<Map<String, dynamic>> countries = [];

  Future<void> loadCountries() async {
    try {
      final res = await api.getCountries();
      // Backend returns 'countries' not 'results'
      countries = List<Map<String, dynamic>>.from(res['countries'] ?? res['results'] ?? []);
      debugPrint('Loaded ${countries.length} countries');
      notifyListeners();
    } catch (e) {
      debugPrint('Failed to load countries: $e');
    }
  }

  // ═══════════════ GLOSSARY ═══════════════
  List<Map<String, dynamic>> glossaryTerms = [];

  Future<void> loadGlossary() async {
    try {
      final res = await api.getGlossary();
      glossaryTerms = List<Map<String, dynamic>>.from(res['results'] ?? []);
      notifyListeners();
    } catch (_) {}
  }

  Future<void> searchGlossary(String query) async {
    try {
      final res = await api.getGlossary(query: query);
      glossaryTerms = List<Map<String, dynamic>>.from(res['results'] ?? []);
      notifyListeners();
    } catch (_) {}
  }

  // ═══════════════ BOOKMARKS ═══════════════
  List<Map<String, dynamic>> bookmarks = [];

  Future<void> loadBookmarks() async {
    try {
      final res = await api.getBookmarks();
      bookmarks = List<Map<String, dynamic>>.from(res['results'] ?? []);
      notifyListeners();
    } catch (_) {}
  }

  Future<void> addBookmark(Map<String, dynamic> data) async {
    final res = await api.createBookmark(data);
    bookmarks.insert(0, res);
    notifyListeners();
  }

  Future<void> removeBookmark(String id) async {
    await api.deleteBookmark(id);
    bookmarks.removeWhere((b) => b['id']?.toString() == id);
    notifyListeners();
  }

  // ═══════════════ REMINDERS ═══════════════
  List<Map<String, dynamic>> reminders = [];

  Future<void> loadReminders() async {
    try {
      final res = await api.getReminders();
      reminders = List<Map<String, dynamic>>.from(res['results'] ?? []);
      notifyListeners();
    } catch (_) {}
  }

  Future<void> addReminder(Map<String, dynamic> data) async {
    final res = await api.createReminder(data);
    reminders.insert(0, res);
    notifyListeners();
  }

  Future<void> editReminder(String id, Map<String, dynamic> data) async {
    final res = await api.updateReminder(id, data);
    final idx = reminders.indexWhere((r) => r['id']?.toString() == id);
    if (idx >= 0) reminders[idx] = res;
    notifyListeners();
  }

  Future<void> removeReminder(String id) async {
    await api.deleteReminder(id);
    reminders.removeWhere((r) => r['id']?.toString() == id);
    notifyListeners();
  }

  // ═══════════════ DOCUMENTS ═══════════════
  List<Map<String, dynamic>> documents = [];

  Future<void> loadDocuments() async {
    try {
      final res = await api.getDocuments();
      documents = List<Map<String, dynamic>>.from(res['results'] ?? []);
      notifyListeners();
    } catch (_) {}
  }

  Future<void> removeDocument(String id) async {
    await api.deleteDocument(id);
    documents.removeWhere((d) => d['id']?.toString() == id);
    notifyListeners();
  }

  // ═══════════════ PROFILE ═══════════════
  Map<String, dynamic>? profile;

  Future<void> loadProfile() async {
    try {
      profile = await api.getProfile();
      // Merge locally-stored country (backend doesn't return it)
      final country = auth.userCountry;
      if (country != null && country.isNotEmpty) {
        profile?['country'] = country;
      }
      notifyListeners();
    } catch (_) {}
  }

  Future<void> updateProfile(Map<String, dynamic> data) async {
    profile = await api.updateProfile(data);
    await auth.updateLocalProfile(data);
    notifyListeners();
  }

  // ═══════════════ STATS ═══════════════
  Map<String, dynamic>? stats;

  Future<void> loadStats() async {
    try {
      stats = await api.getStats();
      notifyListeners();
    } catch (_) {}
  }

  // ═══════════════ LOAD ALL DATA ═══════════════
  Future<void> loadAllData() async {
    await Future.wait([
      loadConversations(),
      loadRightsCards(),
      loadCountries(),
      loadBookmarks(),
      loadDocuments(),
      loadProfile(),
      loadGlossary(),
      loadReminders(),
      loadStats(),
    ]);
  }
}
