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

import 'colors.dart';

class ThemeProvider with ChangeNotifier {
  static const String _themeKey = 'theme_mode';
  static BuildContext? _context;

  bool _isDarkMode = false;

  bool get isDarkMode => _isDarkMode;

  // Set the app context for rebuilding
  static void setContext(BuildContext context) {
    _context = context;
  }

  ThemeProvider() {
    _loadThemeFromPrefs();
  }

  static void _rebuildAllChildren() {
    void rebuild(Element el) {
      el.markNeedsBuild();
      el.visitChildren(rebuild);
    }

    if (_context != null) {
      (_context as Element).visitChildren(rebuild);
    }
  }

  Future<void> _loadThemeFromPrefs() async {
    final prefs = await SharedPreferences.getInstance();
    _isDarkMode = prefs.getBool(_themeKey) ?? false;

    // Update AppColors
    AppColors.setDarkMode(_isDarkMode);

    // Notify listeners after loading
    notifyListeners();
    _rebuildAllChildren();
  }

  Future<void> toggleTheme() async {
    _isDarkMode = !_isDarkMode;

    // Update AppColors
    AppColors.setDarkMode(_isDarkMode);

    // Save to preferences
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_themeKey, _isDarkMode);

    // Notify all listeners to rebuild
    notifyListeners();

    // Force rebuild all children for immediate theme update
    _rebuildAllChildren();
  }

  Future<void> setDarkMode(bool isDark) async {
    if (_isDarkMode == isDark) {
      return;
    }

    _isDarkMode = isDark;

    // Update AppColors
    AppColors.setDarkMode(_isDarkMode);

    // Save to preferences
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_themeKey, _isDarkMode);

    // Notify all listeners to rebuild
    notifyListeners();

    // Force rebuild all children for immediate theme update
    _rebuildAllChildren();
  }
}
