import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/features/settings/data/settings_repository.dart'; // O dove hai messo i metodi del DB
import 'package:flux/features/tasks/models/reminder_default_model.dart';
import 'package:get_it/get_it.dart';

part 'reminder_defaults_state.dart';

class ReminderDefaultsCubit extends Cubit<ReminderDefaultsState> {
  final SettingsRepository _repository = GetIt.I.get<SettingsRepository>();
  final SessionCubit _sessionCubit = GetIt.I.get<SessionCubit>();

  ReminderDefaultsCubit() : super(const ReminderDefaultsState());

  String get _companyId => _sessionCubit.state.company!.id!;
  String get _staffId => _sessionCubit.state.currentStaffMember!.id!;

  Future<void> loadReminders() async {
    emit(state.copyWith(status: ReminderDefaultsStatus.loading));
    try {
      final reminders = await _repository.getMyReminderDefaults(
        companyId: _companyId,
        staffId: _staffId,
      );
      emit(
        state.copyWith(
          status: ReminderDefaultsStatus.success,
          reminders: reminders,
        ),
      );
    } catch (e) {
      emit(
        state.copyWith(
          status: ReminderDefaultsStatus.failure,
          errorMessage: e.toString(),
        ),
      );
    }
  }

  Future<void> addReminder({
    required int minutesBefore,
    required String channel,
  }) async {
    emit(state.copyWith(status: ReminderDefaultsStatus.loading));
    try {
      final newReminder = ReminderDefaultModel(
        companyId: _companyId,
        staffId: _staffId,
        minutesBefore: minutesBefore,
        channel: channel,
      );

      final savedReminder = await _repository.addReminderDefault(newReminder);

      // Aggiungiamo alla lista locale e ordiniamo per minuti
      final updatedList = List<ReminderDefaultModel>.from(state.reminders)
        ..add(savedReminder);
      updatedList.sort((a, b) => a.minutesBefore.compareTo(b.minutesBefore));

      emit(
        state.copyWith(
          status: ReminderDefaultsStatus.success,
          reminders: updatedList,
        ),
      );
    } catch (e) {
      emit(
        state.copyWith(
          status: ReminderDefaultsStatus.failure,
          errorMessage: e.toString(),
        ),
      );
      // Ricarichiamo per sicurezza lo stato precedente
      loadReminders();
    }
  }

  Future<void> deleteReminder(String reminderId) async {
    // Salviamo la lista vecchia nel caso fallisca la cancellazione
    final oldList = List<ReminderDefaultModel>.from(state.reminders);

    // Aggiornamento ottimistico (rimuoviamo subito dalla UI)
    final optimisticList = state.reminders
        .where((r) => r.id != reminderId)
        .toList();
    emit(
      state.copyWith(
        status: ReminderDefaultsStatus.success,
        reminders: optimisticList,
      ),
    );

    try {
      await _repository.deleteReminderDefault(reminderId);
    } catch (e) {
      // Rollback se il DB fallisce
      emit(
        state.copyWith(
          status: ReminderDefaultsStatus.failure,
          errorMessage: e.toString(),
          reminders: oldList,
        ),
      );
    }
  }
}
