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

import '../../../api/marianumcloud/talk/chat/getChatResponse.dart';
import '../../../api/marianumcloud/talk/room/getRoomResponse.dart';
import '../../../theming/appTheme.dart';
import '../../../model/chatList/chatProps.dart';
import '../../../widget/clickableAppBar.dart';
import '../../../widget/loadingSpinner.dart';
import '../../../widget/userAvatar.dart';
import 'chatDetails/chatInfo.dart';
import 'components/chatBubble.dart';
import 'components/chatTextfield.dart';
import 'talkNavigator.dart';

class ChatView extends StatefulWidget {
  final GetRoomResponseObject room;
  final String selfId;
  final UserAvatar avatar;

  const ChatView({super.key, required this.room, required this.selfId, required this.avatar});

  @override
  State<ChatView> createState() => _ChatViewState();
}

class _ChatViewState extends State<ChatView> {

  final ScrollController _listController = ScrollController();

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

  void _query({bool renew = false}) {
    Provider.of<ChatProps>(context, listen: false).setQueryToken(widget.room.token);
  }

  @override
  Widget build(BuildContext context) => Consumer<ChatProps>(
      builder: (context, data, child) {
        var messages = List<Widget>.empty(growable: true);

        if(!data.primaryLoading()) {

          var lastDate = DateTime.now();
          data.getChatResponse.sortByTimestamp().forEach((element) {
            var elementDate = DateTime.fromMillisecondsSinceEpoch(element.timestamp * 1000);

            if(element.systemMessage.contains('reaction')) return;
            var commonRead = int.parse(data.getChatResponse.headers?['x-chat-last-common-read'] ?? '0');

            if(!elementDate.isSameDay(lastDate)) {
              lastDate = elementDate;
              messages.add(ChatBubble(
                context: context,
                isSender: false,
                bubbleData: GetChatResponseObject.getDateDummy(element.timestamp),
                chatData: widget.room,
                refetch: _query,
              ));
            }
            messages.add(
              ChatBubble(
                context: context,
                isSender: element.actorId == widget.selfId && element.messageType == GetRoomResponseObjectMessageType.comment,
                bubbleData: element,
                chatData: widget.room,
                refetch: _query,
                isRead: element.id <= commonRead,
              )
            );
          });

          if(data.getChatResponse.data.length >= 200) {
            messages.insert(0, ChatBubble(
              context: context,
              isSender: false,
              bubbleData: GetChatResponseObject.getTextDummy(
                  'Zurzeit können in dieser App nur die letzten 200 vergangenen Nachrichten angezeigt werden. '
                  'Um ältere Nachrichten abzurufen verwende die Webversion unter https://cloud.marianum-fulda.de'
              ),
              chatData: widget.room,
              refetch: _query,
            ));
          }
        }

        return Scaffold(
          backgroundColor: const Color(0xffefeae2),
          appBar: ClickableAppBar(
            onTap: () {
              TalkNavigator.pushSplitView(context, ChatInfo(widget.room));
            },
            appBar: AppBar(
              title: Row(
                children: [
                  widget.avatar,
                  const SizedBox(width: 10),
                  Expanded(
                    child: Text(widget.room.displayName, overflow: TextOverflow.ellipsis, maxLines: 1),
                  )
                ],
              ),
            ),
          ),
          body: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: const AssetImage('assets/background/chat.png'),
                scale: 1.5,
                opacity: 1,
                repeat: ImageRepeat.repeat,
                invertColors: AppTheme.isDarkMode(context),
              )
            ),
            child: data.primaryLoading() ? const LoadingSpinner() : Column(
              children: [
                Expanded(
                  child: ListView(
                    reverse: true,
                    controller: _listController,
                    children: messages.reversed.toList(),
                  ),
                ),
                Container(
                  color: Theme.of(context).colorScheme.background,
                  child: TalkNavigator.isSecondaryVisible(context)
                      ? ChatTextfield(widget.room.token)
                      : SafeArea(child: ChatTextfield(widget.room.token)
                  ),
                )
              ],
            ),
          ),
        );
      },
    );
}
