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/model/note.dart';
import 'package:hl_lieferservice/feature/delivery/detail/presentation/note/note_edit_dialog.dart';
import 'package:hl_lieferservice/feature/delivery/overview/bloc/tour_bloc.dart';
import 'package:hl_lieferservice/feature/delivery/overview/bloc/tour_state.dart';

import '../../../../../model/delivery.dart';

class NoteListItem extends StatelessWidget {
  final NoteInformation note;
  final String deliveryId;
  final int index;

  const NoteListItem({
    super.key,
    required this.note,
    required this.deliveryId,
    required this.index,
  });

  void _onDelete(BuildContext context) {
    context.read<NoteBloc>().add(RemoveNote(noteId: note.note.id.toString()));
  }

  Widget? _subtitle(BuildContext context) {
    String discountArticleId =
        (context.read<TourBloc>().state as TourLoaded)
            .tour
            .discountArticleNumber;

    if (note.article != null && note.article?.articleNumber == discountArticleId) {
      return const Text("Begründung der Gutschrift");
    }

    return note.article != null ? Text(note.article!.name) : null;
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(0),
      child: ListTile(
        title: Text(note.note.content),
        subtitle: _subtitle(context),
        tileColor: Theme.of(context).colorScheme.surfaceContainerLowest,
        leading: CircleAvatar(child: Text("${index + 1}")),
        trailing: PopupMenuButton(
          itemBuilder: (context) {
            return [
              PopupMenuItem(
                onTap: () {
                  showDialog(
                    context: context,
                    builder: (context) => NoteEditDialog(note: note.note),
                  );
                },
                child: Row(
                  children: [
                    Icon(Icons.edit, color: Colors.blueAccent),
                    Padding(
                      padding: const EdgeInsets.only(left: 5),
                      child: const Text("Editieren"),
                    ),
                  ],
                ),
              ),
              PopupMenuItem(
                onTap: () {
                  _onDelete(context);
                },
                child: Row(
                  children: [
                    Icon(Icons.delete, color: Colors.redAccent),
                    Padding(
                      padding: const EdgeInsets.only(left: 5),
                      child: const Text("Löschen"),
                    ),
                  ],
                ),
              ),
            ];
          },
        ),
      ),
    );
  }
}
