import 'package:auto_size_text/auto_size_text.dart';
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/constraints/app_data.dart';
import 'package:peasmartcare/constraints/image_asset.dart';
import 'package:peasmartcare/models/chat_room_model.dart';
import 'package:peasmartcare/pages/auth/logout.dart';
import 'package:peasmartcare/pages/chat_room/single_chat.dart';
import 'package:peasmartcare/utils/share_data_util.dart';
import 'package:peasmartcare/widgets/empty_box.dart';
import 'package:peasmartcare/widgets/error_box.dart';
import 'package:peasmartcare/widgets/loading.dart';
import 'package:peasmartcare/widgets/not_found_box.dart';
import 'package:peasmartcare/widgets/sweetalert/sweetalert.dart';

class ChatRoomList extends StatefulWidget {
  @override
  _ChatRoomListState createState() => _ChatRoomListState();
}

class _ChatRoomListState extends State<ChatRoomList> {
  @override
  void initState() {
    context.read<ChatRoomListBloc>().add(ChatRoomListGetList(isGroupChat: false));
    super.initState();
  }

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

    return BlocListener<ChatRoomListBloc, ChatRoomListState>(
      listener: (context, state) {
        if (state is ChatRoomListLoaded) {
          if (state.deleteSuccess != null && state.deleteSuccess) {
            SweetAlert.show(
              context,
              subtitle: "ลบข้อมูลสำเร็จ",
              style: SweetAlertStyle.success,
            );

            context.read<ChatRoomListBloc>().add(ChatRoomListGetList());
          } else if (state.deleteSuccess != null && !state.deleteSuccess) {
            SweetAlert.show(
              context,
              subtitle: "ลบข้อมูลไม่สำเร็จ",
              style: SweetAlertStyle.error,
            );
          }
        } else if (state is ChatRoomListErrorUnauthorized) {
          Navigator.of(context).popUntil((route) => route.isFirst);
          Navigator.pushReplacement(
            context,
            MaterialPageRoute(builder: (context) => LogoutPage()),
          );
        }
      },
      child: BlocBuilder<ChatRoomListBloc, ChatRoomListState>(
        builder: (context, state) {
          if (state is ChatRoomListLoading) {
            return Loading();
          } else if (state is ChatRoomListLoaded) {
            List<ChatRoomModel> resultList = state.result;
            return Column(
              children: resultList.map((item) {
                return Center(
                  child: InkWell(
                    child: Container(
                      // constraints: BoxConstraints(
                      //   minWidth: deviceSize.width - 100,
                      //   maxWidth: 370,
                      // ),
                      height: 80,
                      child: Card(
                        color: Colors.grey.withOpacity(0.7),
                        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.yellowColor),
                                      fontWeight: FontWeight.bold,
                                      fontSize: 24,
                                    ),
                                  ),
                                ],
                              ),
                              StreamBuilder(
                                stream: FirebaseFirestore.instance.collection(AppData.cloudFilestoreCollection).doc("chat-masterid-${item.chatMasterId}").snapshots(),
                                builder: (context, snapshot) {
                                  if (!snapshot.hasData) {
                                    // return TableCell(child: _badgeCount(1));
                                    return EmptyBox(heightFactor: 0);
                                  } else {
                                    int runningNumber = snapshot.data["running_number"];
                                    // int _chatCount = ShareDataUtil.getChatNotiCount("chat-masterid-${item.chatMasterId}", runningNumber);
                                    int _chatCount = ShareDataUtil.getChatNotiCount(item.chatMasterId, runningNumber);

                                    return _badgeCount(_chatCount);
                                  }
                                },
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                    onTap: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => SingleChat(
                            fullname: item.customerName,
                            typeChat: item.typeChat,
                            chatMasterId: item.chatMasterId,
                            typeAccount: item.typeAccount,
                          ),
                        ),
                      );
                    },
                  ),
                );
              }).toList(),
            );
          } else if (state is ChatRoomListNotFound) {
            return Column(
              children: [
                SizedBox(height: 50),
                NotFoundBox(),
              ],
            );
          } else if (state is ChatRoomListError) {
            return Column(
              children: [
                SizedBox(height: 50),
                ErrorBox(
                  message: state.message,
                ),
              ],
            );
          }

          return EmptyBox();
        },
      ),
    );
  }

  Widget _buildTable(ChatRoomModel item) {
    Size deviceSize = MediaQuery.of(context).size;

    return InkWell(
      child: Container(
        padding: const EdgeInsets.all(5),
        child: Card(
          elevation: 3,
          child: Container(
            padding: EdgeInsets.all(15),
            width: deviceSize.width - 40,
            height: 150,
            child: ListTile(
              title: Stack(
                //
                children: [
                  Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(item.caNumber),
                      Text(item.customerName),
                      Container(
                        width: deviceSize.width - 50,
                        child: AutoSizeText(
                          item.customerAddress,
                          minFontSize: 8,
                          maxLines: 2,
                        ),
                      ),
                    ],
                  ),
                  Positioned(
                    top: 0,
                    right: 0,
                    child: StreamBuilder(
                        stream: FirebaseFirestore.instance.collection(AppData.cloudFilestoreCollection).doc("chat-masterid-${item.chatMasterId}").snapshots(),
                        builder: (context, snapshot) {
                          if (!snapshot.hasData) {
                            // return TableCell(child: _badgeCount(1));
                            return EmptyBox(heightFactor: 0);
                          } else {
                            int runningNumber = snapshot.data["running_number"];
                            int _chatCount = ShareDataUtil.getChatNotiCount("chat-masterid-${item.chatMasterId}", runningNumber);
                            ShareDataUtil.setChatNotiCount("chat-masterid-${item.chatMasterId}", _chatCount);

                            return _badgeCount(_chatCount);
                          }
                        }),
                  ),
                ],
              ),
              // trailing: Container(
              //   height: 100,
              //   child: StreamBuilder(
              //       stream: FirebaseFirestore.instance.collection(AppData.cloudFilestoreCollection).doc("chat-masterid-${item.chatMasterId}").snapshots(),
              //       builder: (context, snapshot) {
              //         if (!snapshot.hasData) {
              //           // return TableCell(child: _badgeCount(1));
              //           return EmptyBox(heightFactor: 0);
              //         } else {
              //           int runningNumber = snapshot.data["running_number"];
              //           int _chatCount = ShareDataUtil.getChatCount("chat-masterid-${item.chatMasterId}", runningNumber);
              //           ShareDataUtil.setChatCount("chat-masterid-${item.chatMasterId}", _chatCount);

              //           return Text(_chatCount.toString()); //_badgeCount(_chatCount);
              //         }
              //       }),
              // ),
            ),
            // child: Table(
            //   columnWidths: {1: FixedColumnWidth(35)},
            //   children: [
            //     TableRow(
            //       children: [
            //         TableCell(
            //           child: Table(
            //             // columnWidths: {0: FixedColumnWidth(50)},
            //             children: [
            //               TableRow(
            //                 children: [
            //                   TableCell(
            //                     child: Text(item.caNumber),
            //                   ),
            //                 ],
            //               ),
            //               TableRow(
            //                 children: [
            //                   TableCell(
            //                     child: Text(item.customerName),
            //                   ),
            //                 ],
            //               ),
            //               TableRow(
            //                 children: [
            //                   TableCell(
            //                     child: Text(item.customerAddress),
            //                   ),
            //                 ],
            //               ),
            //             ],
            //           ),
            //         ),
            //         StreamBuilder(
            //             stream: FirebaseFirestore.instance.collection(AppData.cloudFilestoreCollection).doc("chat-masterid-${item.chatMasterId}").snapshots(),
            //             builder: (context, snapshot) {
            //               if (!snapshot.hasData) {
            //                 return TableCell(child: _badgeCount(1));
            //               } else {
            //                 int runningNumber = snapshot.data["running_number"];
            //                 int _chatCount = ShareDataUtil.getChatCount("chat-masterid-${item.chatMasterId}", runningNumber);
            //                 ShareDataUtil.setChatCount("chat-masterid-${item.chatMasterId}", _chatCount);

            //                 return TableCell(child: _badgeCount(_chatCount));
            //               }
            //             }),
            //       ],
            //     ),
            //   ],
            // ),
          ),
        ),
      ),
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => SingleChat(
              fullname: item.customerName,
              typeChat: item.typeChat,
              chatMasterId: item.chatMasterId,
              typeAccount: item.typeAccount,
            ),
          ),
        );
      },
    );
  }

  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: 35,
              maxHeight: 35,
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  count <= 99 ? count.toString() : "99+",
                  style: badgeCountStyle,
                  textAlign: TextAlign.center,
                ),
              ],
            ),
          )
        : SizedBox(width: 0);
  }
}
