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

import '../../../api/marianumcloud/talk/createRoom/createRoom.dart';
import '../../../api/marianumcloud/talk/createRoom/createRoomParams.dart';
import '../../../model/chatList/chatListProps.dart';
import '../../../storage/base/settingsProvider.dart';
import '../../../widget/confirmDialog.dart';
import '../../../widget/loadingSpinner.dart';
import 'chatTile.dart';
import 'joinChat.dart';
import 'searchChat.dart';

class ChatList extends StatefulWidget {
  const ChatList({Key? key}) : super(key: key);

  @override
  State<ChatList> createState() => _ChatListState();
}

class _ChatListState extends State<ChatList> {

  @override
  void initState() {
    super.initState();

    FirebaseMessaging.instance.requestPermission(
      provisional: false
    );

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _query();
    });
  }

  void _query({bool renew = false}) {
    Provider.of<ChatListProps>(context, listen: false).run(renew: renew);
  }

  @override
  Widget build(BuildContext context) {
    ChatListProps? latestData;

    return Scaffold(
      appBar: AppBar(
        title: const Text("Talk"),
        actions: [
          IconButton(
            icon: const Icon(Icons.search),
            onPressed: () async {
              if(latestData == null) return;
              showSearch(context: context, delegate: SearchChat(latestData!.getRoomsResponse.data.toList()));
            },
          )
        ],
      ),
      floatingActionButton: FloatingActionButton(
        heroTag: "createChat",
        backgroundColor: Theme.of(context).primaryColor,
        onPressed: () async {
          showSearch(context: context, delegate: JoinChat()).then((username) {
            if(username == null) return;
            
            ConfirmDialog(
              title: "Chat starten",
              content: "Möchtest du einen Chat mit Nutzer '$username' starten?",
              confirmButton: "Chat starten",
              onConfirm: () {
                CreateRoom(CreateRoomParams(
                  roomType: 1,
                  invite: username,
                )).run().then((value) {
                  _query(renew: true);
                });
              },
            ).asDialog(context);
          });
        },
        child: const Icon(Icons.add_comment_outlined),
      ),
      body: Consumer<ChatListProps>(
        builder: (context, data, child) {

          if(data.primaryLoading()) return const LoadingSpinner();

          latestData = data;

          List<ChatTile> chats = [];
          for (var chatRoom in data.getRoomsResponse.sortBy(
            lastActivity: true,
            favoritesToTop: Provider.of<SettingsProvider>(context).val().talkSettings.sortFavoritesToTop,
            unreadToTop: Provider.of<SettingsProvider>(context).val().talkSettings.sortUnreadToTop,
          )
          ) {
            chats.add(ChatTile(data: chatRoom, query: _query));
          }

          return RefreshIndicator(
            color: Theme.of(context).primaryColor,
            onRefresh: () {
              _query(renew: true);
              return Future.delayed(const Duration(seconds: 3));
            },
            child: ListView(children: chats),
          );
        },
      ),
    );
  }
}