import 'package:flutter/material.dart';

import '../../../routing/app_routes.dart';
import '../../../state/app/infrastructure/loadable_state/loadable_state.dart';
import '../../../state/app/infrastructure/loadable_state/view/loadable_state_consumer.dart';
import '../../../state/app/infrastructure/utility_widgets/bloc_module.dart';
import '../../../state/app/modules/marianum_message/bloc/marianum_message_bloc.dart';
import '../../../state/app/modules/marianum_message/bloc/marianum_message_state.dart';
import '../../../widget/centered_leading.dart';
import 'search_marianum_messages.dart';

class MarianumMessageListView extends StatelessWidget {
  const MarianumMessageListView({super.key});

  @override
  Widget build(
    BuildContext context,
  ) => BlocModule<MarianumMessageBloc, LoadableState<MarianumMessageState>>(
    create: (context) => MarianumMessageBloc(),
    child: (context, bloc, state) => Scaffold(
      appBar: AppBar(
        title: const Text('Marianum Message'),
        actions: [
          IconButton(
            tooltip: 'Suchen',
            icon: const Icon(Icons.search),
            onPressed: () {
              final list = bloc.state.data?.messageList;
              if (list == null) return;
              showSearch(
                context: context,
                delegate: SearchMarianumMessages(
                  base: list.base,
                  messages: list.messages,
                ),
              );
            },
          ),
        ],
      ),
      body: LoadableStateConsumer<MarianumMessageBloc, MarianumMessageState>(
        child: (state, loading) => ListView.builder(
          itemCount: state.messageList.messages.length,
          itemBuilder: (context, index) {
            var message = state.messageList.messages[index];
            return ListTile(
              leading: const CenteredLeading(Icon(Icons.newspaper)),
              title: Text(message.name, overflow: TextOverflow.ellipsis),
              subtitle: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  if (message.description.isNotEmpty)
                    Text(
                      message.description,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  Text('vom ${message.date}'),
                ],
              ),
              trailing: const Icon(Icons.arrow_right),
              onTap: () {
                AppRoutes.openMarianumMessage(context, message);
              },
            );
          },
        ),
      ),
    ),
  );
}
