import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../models/school.dart';
import '../models/user_settings.dart';
import '../models/school_settings.dart';
import '../services/settings_api.dart';

class AppState extends ChangeNotifier {
  String? token;
  School? school;
  String? userFirstName;

  UserSettings? userSettings;
  SchoolSettings? schoolSettings;

  bool loadingSettings = false;
  String settingsError = '';

  // Call this after login + school selection (not in SelectSchoolPage UI itself)
  Future<void> bootstrap({
    required String token,
    required School school,
    String? userFirstName,
  }) async {
    this.token = token;
    this.school = school;
    this.userFirstName = userFirstName;

    loadingSettings = true;
    settingsError = '';
    notifyListeners();

    // Try cache first
    await _loadCache();

    try {
      // Fetch both in parallel
      final results = await Future.wait([
        SettingsApi.fetchUserSettings(token: token),
        SettingsApi.fetchSchoolSettings(token: token, schoolId: school.id),
      ]);

      userSettings = results[0] as UserSettings;
      schoolSettings = results[1] as SchoolSettings;

      await _saveCache();
    } catch (e) {
      settingsError = e.toString();
      // If cache exists, we keep it and don't crash the app
    } finally {
      loadingSettings = false;
      notifyListeners();
    }
  }

  // If you want manual refresh from any page
  Future<void> refreshSettings() async {
    if (token == null || school == null) return;
    await bootstrap(
      token: token!,
      school: school!,
      userFirstName: userFirstName,
    );
  }

  String get _cacheKey {
    final sid = school?.id ?? 0;
    // Cache per school (user is implicit in token/session)
    return 'settings_cache_school_$sid';
  }

  Future<void> _saveCache() async {
    if (userSettings == null || schoolSettings == null) return;
    final sp = await SharedPreferences.getInstance();

    final payload = jsonEncode({
      'user': userSettings!.toMap(),
      'school': schoolSettings!.toMap(),
    });

    await sp.setString(_cacheKey, payload);
  }

  Future<void> _loadCache() async {
    final sp = await SharedPreferences.getInstance();
    final raw = sp.getString(_cacheKey);
    if (raw == null) return;

    try {
      final decoded = jsonDecode(raw) as Map<String, dynamic>;
      userSettings = UserSettings.fromMap(
        (decoded['user'] as Map).cast<String, dynamic>(),
      );
      schoolSettings = SchoolSettings.fromMap(
        (decoded['school'] as Map).cast<String, dynamic>(),
      );
    } catch (_) {
      // Ignore cache errors
    }
  }
}
