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

/// Service for managing app theme preferences
class ThemeService {
  static const String _themeKey = 'app_theme_mode';
  static const ThemeMode _defaultTheme = ThemeMode.light;

  /// Get current theme mode from storage
  static Future<ThemeMode> getThemeMode() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final themeString = prefs.getString(_themeKey);

      if (themeString == null) {
        return _defaultTheme;
      }

      switch (themeString) {
        case 'ThemeMode.light':
          return ThemeMode.light;
        case 'ThemeMode.dark':
          return ThemeMode.dark;
        case 'ThemeMode.system':
          return ThemeMode.system;
        default:
          return _defaultTheme;
      }
    } catch (e) {
      Logger.error('Error getting theme mode: $e');
      return _defaultTheme;
    }
  }

  /// Save theme mode to storage
  static Future<void> setThemeMode(ThemeMode themeMode) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString(_themeKey, themeMode.toString());
      Logger.info('Theme mode saved: ${themeMode.toString()}');
    } catch (e) {
      Logger.error('Error saving theme mode: $e');
    }
  }

  /// Get theme mode from storage (for future use)
  static Future<ThemeMode> getStoredThemeMode() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final themeString = prefs.getString(_themeKey);

      if (themeString == null) {
        return _defaultTheme;
      }

      switch (themeString) {
        case 'ThemeMode.light':
          return ThemeMode.light;
        case 'ThemeMode.dark':
          return ThemeMode.dark;
        case 'ThemeMode.system':
          return ThemeMode.system;
        default:
          return _defaultTheme;
      }
    } catch (e) {
      Logger.error('Error getting stored theme mode: $e');
      return _defaultTheme;
    }
  }

  /// Check if dark mode is available (for future settings)
  static bool isDarkModeAvailable() {
    // Dark mode is now available
    return true;
  }

  /// Get theme mode string for display
  static String getThemeModeString(ThemeMode themeMode) {
    switch (themeMode) {
      case ThemeMode.light:
        return 'Light Mode';
      case ThemeMode.dark:
        return 'Dark Mode';
      case ThemeMode.system:
        return 'System Default';
    }
  }

  /// Reset theme to default
  static Future<void> resetTheme() async {
    await setThemeMode(_defaultTheme);
  }
}
