import 'dart:typed_data';

import 'package:flutter/cupertino.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hl_lieferservice/model/delivery.dart';
import 'package:hl_lieferservice/widget/operations/bloc/operation_bloc.dart';
import 'package:hl_lieferservice/widget/operations/bloc/operation_event.dart';

import 'note_event.dart';
import 'note_state.dart';
import 'package:hl_lieferservice/feature/delivery/detail/repository/note_repository.dart';

class NoteBloc extends Bloc<NoteEvent, NoteState> {
  final NoteRepository repository;
  final OperationBloc opBloc;

  NoteBloc({required this.repository, required this.opBloc})
    : super(NoteInitial()) {
    on<LoadNote>(_load);
    on<AddNote>(_add);
    on<EditNote>(_edit);
    on<RemoveNote>(_remove);
    on<AddImageNote>(_upload);
    on<RemoveImageNote>(_removeImage);
  }

  Future<void> _removeImage(
    RemoveImageNote event,
    Emitter<NoteState> emit,
  ) async {
    opBloc.add(LoadOperation());

    try {
      final currentState = state;
      await repository.deleteImage(event.deliveryId, event.objectId);

      if (currentState is NoteLoaded) {
        emit.call(
          currentState.copyWith(
            images:
                currentState.images
                    .where((image) => image.$1.objectId != event.objectId)
                    .toList(),
          ),
        );
      }

      opBloc.add(FinishOperation());
    } catch (e, st) {
      debugPrint("Fehler beim Löschen des Bildes: $e");
      debugPrint(st.toString());

      opBloc.add(FailOperation(message: e.toString()));
    }
  }

  Future<void> _upload(AddImageNote event, Emitter<NoteState> emit) async {
    opBloc.add(LoadOperation());

    try {
      final currentState = state;
      Uint8List imageBytes = await event.file.readAsBytes();
      ImageNote note = await repository.addImage(event.deliveryId, imageBytes);

      if (currentState is NoteLoaded) {
        emit.call(
          currentState.copyWith(
            images: [...currentState.images, (note, imageBytes)],
          ),
        );
      }

      opBloc.add(FinishOperation());
    } catch (e, st) {
      debugPrint("Fehler beim Hinzufügen des Bildes: $e");
      debugPrint(st.toString());

      opBloc.add(FailOperation(message: e.toString()));
    }
  }

  Future<void> _load(LoadNote event, Emitter<NoteState> emit) async {
    emit.call(NoteLoading());

    try {
      List<String> urls =
          event.delivery.images.map((image) => image.url).toList();
      List<Note> notes = await repository.loadNotes(event.delivery.id);
      List<NoteTemplate> templates = await repository.loadTemplates();
      List<Uint8List> images = await repository.loadImages(urls);

      emit.call(
        NoteLoaded(
          notes: notes,
          templates: templates,
          images: List.generate(
            images.length,
            (index) => (event.delivery.images[index], images[index]),
          ),
        ),
      );
      opBloc.add(FinishOperation());
    } catch (e, st) {
      debugPrint("Fehler beim Herunterladen der Notizen: $e");
      debugPrint(st.toString());

      opBloc.add(
        FailOperation(message: "Notizen konnten nicht heruntergeladen werden."),
      );

      emit.call(NoteLoadingFailed());
    }
  }

  Future<void> _add(AddNote event, Emitter<NoteState> emit) async {
    opBloc.add(LoadOperation());

    try {
      final currentState = state;
      Note note = await repository.addNote(event.deliveryId, event.note);

      if (currentState is NoteLoaded) {
        List<Note> refreshedNotes = [...currentState.notes, note];
        emit.call(currentState.copyWith(notes: refreshedNotes));
      }

      opBloc.add(FinishOperation());
    } catch (e, st) {
      debugPrint("Fehler beim Hinzufügen der Notiz: $e");
      debugPrint(st.toString());

      opBloc.add(FailOperation(message: e.toString()));
    }
  }

  Future<void> _edit(EditNote event, Emitter<NoteState> emit) async {
    opBloc.add(LoadOperation());

    try {
      final currentState = state;
      await repository.editNote(event.noteId, event.content);

      if (currentState is NoteLoaded) {
        List<Note> refreshedNotes = [
          ...currentState.notes.where(
            (note) => note.id != int.parse(event.noteId),
          ),
          Note(content: event.content, id: int.parse(event.noteId)),
        ];
        emit.call(currentState.copyWith(notes: refreshedNotes));
      }

      opBloc.add(FinishOperation());
    } catch (e, st) {
      debugPrint("Fehler beim Hinzufügen der Notiz: $e");
      debugPrint(st.toString());

      opBloc.add(FailOperation(message: e.toString()));
    }
  }

  Future<void> _remove(RemoveNote event, Emitter<NoteState> emit) async {
    opBloc.add(LoadOperation());

    try {
      final currentState = state;
      await repository.deleteNote(event.noteId);

      if (currentState is NoteLoaded) {
        List<Note> refreshedNotes =
            currentState.notes
                .where((note) => note.id != int.parse(event.noteId))
                .toList();

        emit.call(currentState.copyWith(notes: refreshedNotes));
      }

      opBloc.add(FinishOperation());
    } catch (e, st) {
      debugPrint("Fehler beim Hinzufügen der Notiz: $e");
      debugPrint(st.toString());

      opBloc.add(
        FailOperation(message: "Notizen konnte nicht gelöscht werden."),
      );
    }
  }
}
