
import 'dart:async';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter_split_view/flutter_split_view.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 '../../../notification/notifyUpdater.dart';
import '../../../storage/base/settingsProvider.dart';
import '../../../widget/confirmDialog.dart';
import '../../../widget/loadingSpinner.dart';
import 'components/chatTile.dart';
import 'components/splitViewPlaceholder.dart';
import 'joinChat.dart';
import 'searchChat.dart';

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

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

class _ChatListState extends State<ChatList> {
  late SettingsProvider settings;

  @override
  void initState() {
    super.initState();
    settings = Provider.of<SettingsProvider>(context, listen: false);

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

      if(!settings.val().notificationSettings.enabled && !settings.val().notificationSettings.askUsageDismissed) {
        settings.val(write: true).notificationSettings.askUsageDismissed = true;

        ConfirmDialog(
          icon: Icons.notifications_active_outlined,
          title: "Benachrichtigungen aktivieren",
          content: "Auf wunsch kannst du Push-Benachrichtigungen aktivieren. Deine Einstellungen kannst du jederzeit ändern.",
          confirmButton: "Weiter",
          onConfirm: () {
            FirebaseMessaging.instance.requestPermission(
                provisional: false
            ).then((value) {
              switch (value.authorizationStatus) {
                case AuthorizationStatus.authorized:
                  NotifyUpdater.enableAfterDisclaimer(settings).asDialog(context);
                  break;
                case AuthorizationStatus.denied:
                  showDialog(context: context, builder: (context) => const AlertDialog(
                    content: Text("Du kannst die Benachrichtigungen später jederzeit in den App-Einstellungen aktivieren."),
                  ));
                  break;
                default:
                  break;
              }
            });
          },
        ).asDialog(context);
      }
    });
  }

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

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

    return SplitView.material(
      placeholder: const SplitViewPlaceholder(),
      breakpoint: 1000,
      child: 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,
            )
            ) {
              bool hasDraft = settings.val().talkSettings.drafts.containsKey(chatRoom.token);
              chats.add(ChatTile(data: chatRoom, query: _query, hasDraft: hasDraft));
            }

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