import 'dart:developer';

import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:krow/core/application/di/injectable.dart';
import 'package:krow/core/data/enums/state_status.dart';
import 'package:krow/features/profile/live_photo/data/models/live_photo_data.dart';
import 'package:krow/features/profile/live_photo/domain/staff_live_photo_repository.dart';

part 'live_photo_event.dart';

part 'live_photo_state.dart';

class LivePhotoBloc extends Bloc<LivePhotoEvent, LivePhotoState> {
  LivePhotoBloc() : super(const LivePhotoState()) {
    on<InitLivePhotoBloc>((event, emit) async {
      emit(state.copyWith(status: StateStatus.loading));

      try {
        await for (final photoData
            in _repository.getStaffLivePhotoWithCache()) {
          emit(
            state.copyWith(
              status: StateStatus.idle,
              photoData: photoData,
            ),
          );
        }
      } catch (except) {
        log(
          except.toString(),
          error: except,
        );
      }

      emit(state.copyWith(status: StateStatus.idle));
    });

    on<AddNewPhotoEvent>((event, emit) async {
      final photoData = LivePhotoData(
        id: null,
        imageUrl: null,
        imagePath: event.newImagePath,
        status: LivePhotoStatus.pending,
        timestamp: DateTime.now(),
      );

      emit(state.copyWith(photoData: photoData));

      try {
        await _repository.uploadStaffLivePhoto(photoData);
      } catch (except) {
        log(
          except.toString(),
          error: except,
        );

        emit(
          state.copyWith(
            photoData: state.photoData?.copyWith(
              status: LivePhotoStatus.declined,
            ),
          ),
        );
      }
    });

    on<DeleteCurrentPhotoEvent>((event, emit) async {
      emit(state.removeCurrentPhoto(status: StateStatus.loading));

      //TODO: Add photo deletion once backend implements the mutation
      await Future<void>.delayed(const Duration(seconds: 1));

      emit(state.copyWith(status: StateStatus.idle));
    });
  }

  final StaffLivePhotoRepository _repository =
      getIt<StaffLivePhotoRepository>();
}
