import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hl_lieferservice/feature/delivery/detail/bloc/note_bloc.dart';
import 'package:hl_lieferservice/feature/delivery/detail/bloc/note_event.dart';
import 'package:hl_lieferservice/feature/delivery/detail/bloc/note_state.dart';
import 'package:hl_lieferservice/feature/delivery/detail/model/note.dart';
import 'package:hl_lieferservice/feature/delivery/detail/presentation/note/note_overview.dart';
import 'package:hl_lieferservice/model/delivery.dart';

class DeliveryStepNote extends StatefulWidget {
  final Delivery delivery;

  const DeliveryStepNote({required this.delivery, super.key});

  @override
  State<StatefulWidget> createState() => _DeliveryStepInfo();
}

class _DeliveryStepInfo extends State<DeliveryStepNote> {
  @override
  void initState() {
    super.initState();
    context.read<NoteBloc>().add(LoadNote(delivery: widget.delivery));
  }

  Widget _notesLoadingFailed() {
    return Center(child: Text("Notizen können nicht heruntergeladen werden.."));
  }

  Widget _notesLoading() {
    return Center(child: CircularProgressIndicator());
  }

  Widget _blocUndefinedState() {
    return Center(child: const Text("NoteBloc in einem Fehlerhaften Zustand"));
  }

  Widget _notesOverview(
    BuildContext context,
    List<Note> notes,
    List<NoteTemplate> templates,
    List<(ImageNote, Uint8List)> images,
  ) {
    List<NoteInformation> hydratedNotes =
        notes
            .map(
              (note) => NoteInformation(
                note: note,
                article: widget.delivery.findArticleWithNoteId(
                  note.id.toString(),
                ),
              ),
            )
            .toList();

    return NoteOverview(
      notes: hydratedNotes,
      deliveryId: widget.delivery.id,
      templates: templates,
      images: images,
    );
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<NoteBloc, NoteState>(
      builder: (context, state) {
        if (state is NoteLoading) {
          return _notesLoading();
        }

        if (state is NoteLoaded) {
          return _notesOverview(
            context,
            state.notes,
            state.templates,
            state.images,
          );
        }

        if (state is NoteLoadingFailed) {
          return _notesLoadingFailed();
        }

        return _blocUndefinedState();
      },
    );
  }
}
