import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../../../../model/message/messageProps.dart';
import '../../../../widget/loadingSpinner.dart';
import 'messageView.dart';


class Message extends StatefulWidget {
  const Message({super.key});

  @override
  State<Message> createState() => _MessageState();
}

class _MessageState extends State<Message> {
  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      Provider.of<MessageProps>(context, listen: false).run();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) => Scaffold(
      appBar: AppBar(
        title: const Text('Marianum Message'),
      ),
      body: Consumer<MessageProps>(builder: (context, value, child) {
        if(value.primaryLoading()) return const LoadingSpinner();

        return RefreshIndicator(
          child: ListView.builder(
              itemCount: value.getMessagesResponse.messages.length,
              itemBuilder: (context, index) {
                var message = value.getMessagesResponse.messages.toList()[index];
                return ListTile(
                  leading: const Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [Icon(Icons.newspaper)],
                  ),
                  title: Text(message.name, overflow: TextOverflow.ellipsis),
                  subtitle: Text('vom ${message.date}'),
                  trailing: const Icon(Icons.arrow_right),
                  onTap: () {
                    Navigator.push(context, MaterialPageRoute(builder: (context) => MessageView(basePath: value.getMessagesResponse.base, message: message)));
                  },
                );
              }
          ),
          onRefresh: () {
            Provider.of<MessageProps>(context, listen: false).run(renew: true);
            return Future.delayed(const Duration(seconds: 3));
          },
        );
      }),
    );
}
