import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../services/theme_service.dart';

/// Provider for theme management
final themeProvider = StateNotifierProvider<ThemeNotifier, ThemeMode>((ref) {
  return ThemeNotifier();
});

/// Notifier for managing theme state
class ThemeNotifier extends StateNotifier<ThemeMode> {
  ThemeNotifier() : super(ThemeMode.light) {
    _initializeTheme();
  }

  /// Initialize theme from storage
  Future<void> _initializeTheme() async {
    try {
      final storedTheme = await ThemeService.getThemeMode();
      state = storedTheme;
    } catch (e) {
      state = ThemeMode.light;
    }
  }

  /// Change theme mode
  Future<void> setThemeMode(ThemeMode themeMode) async {
    state = themeMode;
    await ThemeService.setThemeMode(themeMode);
  }

  /// Toggle between light and dark mode
  Future<void> toggleTheme() async {
    final newTheme = state == ThemeMode.light
        ? ThemeMode.dark
        : ThemeMode.light;
    await setThemeMode(newTheme);
  }

  /// Reset to default theme
  Future<void> resetTheme() async {
    await setThemeMode(ThemeMode.light);
  }

  /// Check if current theme is dark
  bool isDarkMode() {
    return state == ThemeMode.dark;
  }

  /// Check if current theme is light
  bool isLightMode() {
    return state == ThemeMode.light;
  }

  /// Get current theme as string
  String get currentThemeString {
    return ThemeService.getThemeModeString(state);
  }

  /// Initialize theme from storage (for future use)
  Future<void> initializeTheme() async {
    final storedTheme = await ThemeService.getStoredThemeMode();
    // Only set if dark mode is available or if it's light mode
    if (storedTheme == ThemeMode.light || ThemeService.isDarkModeAvailable()) {
      state = storedTheme;
    }
  }
}

/// Provider for checking if dark mode is available
final isDarkModeAvailableProvider = Provider<bool>((ref) {
  return ThemeService.isDarkModeAvailable();
});

/// Provider for current theme string
final themeStringProvider = Provider<String>((ref) {
  final theme = ref.watch(themeProvider);
  return ThemeService.getThemeModeString(theme);
});
