
import 'package:flutter/material.dart';
import 'package:loader_overlay/loader_overlay.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/loadingSpinner.dart';
import 'chatBubble.dart';
import 'chatTextfield.dart';

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

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

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

class _ChatViewState extends State<ChatView> {

  final ScrollController _listController = ScrollController();

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

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

  void _query({bool renew = false}) {
    Provider.of<ChatProps>(context, listen: false).setQueryToken(widget.room.token);
  }
  
  @override
  Widget build(BuildContext context) {
    return Consumer<ChatProps>(
      builder: (context, data, child) {
        List<Widget> messages = List<Widget>.empty(growable: true);

        if(!data.primaryLoading()) {

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

            if(element.systemMessage.contains("reaction")) return;

            if(elementDate.weekday != lastDate.weekday) {
              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
              )
            );
          });
        }

        return Scaffold(
          backgroundColor: const Color(0xffefeae2),
          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: LoaderOverlay(
              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: SafeArea(child: ChatTextfield(widget.room.token)),
                  )
                ],
              ),
            )
          ),
        );
      },
    );
  }
}
