import 'package:bloc/bloc.dart';
import 'package:shared_preferences/shared_preferences.dart';

// Events
abstract class GridPreferenceEvent {}

class LoadGridPreference extends GridPreferenceEvent {}

class ToggleGridPreference extends GridPreferenceEvent {}

// States
abstract class GridPreferenceState {}

class GridPreferenceInitial extends GridPreferenceState {}

class GridPreferenceLoading extends GridPreferenceState {}

class GridPreferenceLoaded extends GridPreferenceState {
  final bool isGrid;

  GridPreferenceLoaded({required this.isGrid});

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
    return other is GridPreferenceLoaded && other.isGrid == isGrid;
  }

  @override
  int get hashCode => isGrid.hashCode;
}

class GridPreferenceError extends GridPreferenceState {
  final String message;

  GridPreferenceError({required this.message});

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
    return other is GridPreferenceError && other.message == message;
  }

  @override
  int get hashCode => message.hashCode;
}

// BLoC
class GridPreferenceBloc extends Bloc<GridPreferenceEvent, GridPreferenceState> {
  GridPreferenceBloc() : super(GridPreferenceInitial()) {
    on<LoadGridPreference>(_onLoadGridPreference);
    on<ToggleGridPreference>(_onToggleGridPreference);
  }

  Future<void> _onLoadGridPreference(
    LoadGridPreference event,
    Emitter<GridPreferenceState> emit,
  ) async {
    emit(GridPreferenceLoading());
    try {
      final prefs = await SharedPreferences.getInstance();
      final isGrid = prefs.getBool('isGridMode') ?? false;
      emit(GridPreferenceLoaded(isGrid: isGrid));
    } catch (e) {
      emit(GridPreferenceError(message: 'Gagal memuat preferensi grid'));
    }
  }

  Future<void> _onToggleGridPreference(
    ToggleGridPreference event,
    Emitter<GridPreferenceState> emit,
  ) async {
    if (state is GridPreferenceLoaded) {
      final currentState = state as GridPreferenceLoaded;
      final newValue = !currentState.isGrid;
      
      try {
        final prefs = await SharedPreferences.getInstance();
        await prefs.setBool('isGridMode', newValue);
        emit(GridPreferenceLoaded(isGrid: newValue));
      } catch (e) {
        emit(GridPreferenceError(message: 'Gagal menyimpan preferensi grid'));
        // Kembalikan ke state sebelumnya jika gagal menyimpan
        emit(currentState);
      }
    }
  }
}