import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:peasmartcare/blocs/chat_room_list/chat_room_list_bloc.dart';
import 'package:peasmartcare/components/body_layout.dart';
import 'package:peasmartcare/components/customer_info.dart';
import 'package:peasmartcare/components/header_content.dart';
import 'package:peasmartcare/components/pea_app_bar.dart';
import 'package:peasmartcare/components/pea_bottom_bar.dart';
import 'package:peasmartcare/components/profile_avatar.dart';
import 'package:peasmartcare/constraints/app_data.dart';
import 'package:peasmartcare/constraints/image_asset.dart';
import 'package:peasmartcare/pages/chat_room/chat_room_list.dart';
import 'package:peasmartcare/pages/chat_room/group_chat.dart';
import 'package:peasmartcare/utils/share_data_util.dart';
import 'package:peasmartcare/widgets/empty_box.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class ChatRoomPage extends StatefulWidget {
  @override
  _ChatRoomPageState createState() => _ChatRoomPageState();
}

class _ChatRoomPageState extends State<ChatRoomPage> {
  RefreshController _refreshController = RefreshController(initialRefresh: false);

  @override
  Widget build(BuildContext context) {
    Size deviceSize = MediaQuery.of(context).size;

    return Scaffold(
      appBar: PEAAppBar(
        title: "ห้องสนทนา",
        actions: <Widget>[
          ProfileAvatar(),
        ],
      ),
      bottomNavigationBar: PEABottomBar(initialActiveIndex: 3),
      body: BodyLayout(
        header: CustomerInfo(),
        onPullRefresh: _onRefresh,
        refreshController: _refreshController,
        child: Column(
          children: <Widget>[
            Center(
              child: InkWell(
                child: Container(
                  // constraints: BoxConstraints(
                  //   minWidth: deviceSize.width - 100,
                  //   // maxWidth: 370,
                  // ),
                  height: 80,
                  child: Card(
                    color: Color(AppData.yellowColor),
                    child: Padding(
                      padding: const EdgeInsets.only(left: 15, right: 10),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Row(
                            children: [
                              Image.asset(
                                ImageAsset.chatRoomImg,
                                height: 40,
                              ),
                              SizedBox(width: 15),
                              Text(
                                "ห้องสนทนารวม",
                                style: TextStyle(
                                  color: Color(AppData.purpleColor),
                                  fontWeight: FontWeight.bold,
                                  fontSize: 24,
                                ),
                              ),
                            ],
                          ),
                          StreamBuilder(
                              stream: FirebaseFirestore.instance.collection(AppData.cloudFilestoreCollection).doc("chat-masterid-${AppData.groupChatChatMasterId}").snapshots(),
                              builder: (context, snapshot) {
                                if (!snapshot.hasData) {
                                  return EmptyBox(heightFactor: 0);
                                } else {
                                  int runningNumber = snapshot.data["running_number"];
                                  int _chatCount = ShareDataUtil.getChatNotiCount(AppData.groupChatChatMasterId, runningNumber);

                                  return _badgeCount(_chatCount);
                                }
                              })
                          // Image.asset(ImageAsset.chatRoomPurpleImg, height: 40)
                        ],
                      ),
                    ),
                  ),
                ),
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => GroupChat(chatMasterId: AppData.groupChatChatMasterId)),
                  );
                },
              ),
            ),
            ChatRoomList(),
          ],
        ),
      ),
    );
  }

  Widget _body() {
    return Positioned(
      child: Padding(
        padding: const EdgeInsets.only(top: 160),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ChatRoomList(),
          ],
        ),
      ),
    );
  }

  Future<void> _onRefresh() async {
    context.read<ChatRoomListBloc>().add(ChatRoomListGetList());

    await Future.delayed(Duration(milliseconds: 1000));
    _refreshController.refreshCompleted();
  }

  Widget _badgeCount(int count) {
    TextStyle badgeCountStyle = TextStyle(color: Colors.white, fontSize: 15);
    return (count > 0)
        ? Container(
            padding: EdgeInsets.all(1),
            decoration: BoxDecoration(
              color: Colors.red,
              borderRadius: BorderRadius.circular(50),
            ),
            width: 35,
            constraints: BoxConstraints(
              // maxWidth: 65,
              maxHeight: 35,
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  count <= 99 ? count.toString() : "99+",
                  style: badgeCountStyle,
                  textAlign: TextAlign.center,
                ),
              ],
            ),
          )
        : EmptyBox(heightFactor: 0);
  }
}
