import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'theme_event.dart';
import 'theme_state.dart';

/// BLoC for managing application theme preferences.
/// 
/// This BLoC handles theme-related events and manages the application's
/// theme mode (light, dark, or system). It persists theme preferences
/// using SharedPreferences for consistency across app sessions.
class ThemeBloc extends Bloc<ThemeEvent, ThemeState> {
  /// Creates a new [ThemeBloc] with default theme state.
  /// 
  /// Registers event handlers for theme changes and loading saved preferences.
  ThemeBloc() : super(const ThemeState()) {
    on<ThemeChanged>(_onThemeChanged);
    on<ThemeLoadRequested>(_onThemeLoadRequested);
  }

  /// Handles [ThemeChanged] events.
  /// 
  /// Updates the theme mode and persists the preference to local storage.
  /// This ensures the theme choice is remembered across app restarts.
  Future<void> _onThemeChanged(
    ThemeChanged event,
    Emitter<ThemeState> emit,
  ) async {
    emit(state.copyWith(themeMode: event.themeMode));
    
    // Save the theme preference to persistent storage
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('themeMode', event.themeMode.toString());
  }

  /// Handles [ThemeLoadRequested] events.
  /// 
  /// Loads the saved theme preference from SharedPreferences and applies it.
  /// If no preference is saved, the theme remains as system default.
  Future<void> _onThemeLoadRequested(
    ThemeLoadRequested event,
    Emitter<ThemeState> emit,
  ) async {
    final prefs = await SharedPreferences.getInstance();
    final themeModeString = prefs.getString('themeMode');

    if (themeModeString != null) {
      ThemeMode themeMode;
      switch (themeModeString) {
        case 'ThemeMode.light':
          themeMode = ThemeMode.light;
          break;
        case 'ThemeMode.dark':
          themeMode = ThemeMode.dark;
          break;
        default:
          themeMode = ThemeMode.system;
      }
      emit(state.copyWith(themeMode: themeMode));
    }
  }
}