import 'package:flutter_bloc/flutter_bloc.dart';
import '../viewmodels/scan_history_viewmodel.dart';
import '../models/scan_history_model.dart';

// EVENTS
abstract class ScanHistoryEvent {}

class LoadScanHistory extends ScanHistoryEvent {}

class UpdateDate extends ScanHistoryEvent {
  final DateTime date;
  UpdateDate(this.date);
}

class UpdateStatus extends ScanHistoryEvent {
  final String status;
  UpdateStatus(this.status);
}

// STATES
class ScanHistoryState {
  final DateTime selectedDate;
  final String selectedStatus;
  final bool isLoading;
  final List<ScanHistoryModel> history;
  final String? error;

  ScanHistoryState({
    required this.selectedDate,
    required this.selectedStatus,
    required this.isLoading,
    required this.history,
    this.error,
  });

  factory ScanHistoryState.initial() => ScanHistoryState(
    selectedDate: DateTime.now(),
    selectedStatus: 'All Status',
    isLoading: false,
    history: [],
  );

  ScanHistoryState copyWith({
    DateTime? selectedDate,
    String? selectedStatus,
    bool? isLoading,
    List<ScanHistoryModel>? history,
    String? error,
  }) {
    return ScanHistoryState(
      selectedDate: selectedDate ?? this.selectedDate,
      selectedStatus: selectedStatus ?? this.selectedStatus,
      isLoading: isLoading ?? this.isLoading,
      history: history ?? this.history,
      error: error,
    );
  }
}

// BLOC
class ScanHistoryBloc extends Bloc<ScanHistoryEvent, ScanHistoryState> {
  final ScanHistoryViewModel viewModel;

  ScanHistoryBloc({required this.viewModel}) : super(ScanHistoryState.initial()) {
    on<LoadScanHistory>(_onLoadHistory);
    on<UpdateDate>(_onUpdateDate);
    on<UpdateStatus>(_onUpdateStatus);
  }

  Future<void> _onLoadHistory(LoadScanHistory event, Emitter<ScanHistoryState> emit) async {
    emit(state.copyWith(isLoading: true));
    try {
      final data = await viewModel.getScanHistory(state.selectedDate, state.selectedStatus);
      emit(state.copyWith(isLoading: false, history: data, error: null));
    } catch (_) {
      emit(state.copyWith(isLoading: false, error: "Error loading data"));
    }
  }

  void _onUpdateDate(UpdateDate event, Emitter<ScanHistoryState> emit) {
    emit(state.copyWith(selectedDate: event.date));
    add(LoadScanHistory());
  }

  void _onUpdateStatus(UpdateStatus event, Emitter<ScanHistoryState> emit) {
    emit(state.copyWith(selectedStatus: event.status));
    add(LoadScanHistory());
  }
}
