import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:mwf_app/service/notification_count.dart';
import 'package:mwf_app/Service/strings.dart';
import 'package:mwf_app/service/url.dart';
import 'package:mwf_app/service/pref.dart';
import 'package:mwf_app/service/screen.dart';
import 'package:mwf_app/set7/chat_page.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:provider/provider.dart';

class ChatListViewItem extends StatelessWidget {
  final String chatRoomId;
  final String image;
  final String id;
  final String name;
  final String address;
  final String time;
  final bool hasUnreadMessage;
  static int newMesssageCount;
  final newCount;
  final String chatMasterId;
  final String accountId;
  final String typeAccount;
  final String customerID;
  final String customerCA;
  final String typeChat;
  final String inCa;
  static String seleInfo;
  static String tsicid;
  static String branchId;
  
  const ChatListViewItem({
    this.chatRoomId,
    this.image,
    this.name,
    this.id,
    this.address,
    this.time,
    this.hasUnreadMessage,
    this.newCount,
    this.chatMasterId,
    this.accountId,
    this.typeAccount,
    this.customerID,
    this.customerCA,
    this.typeChat,
    this.inCa
  });

  // static getNumber(custoCa, chatMasterId) async {
  //   if(custoCa != ""){
  //     var number = await getPref("int", custoCa);
  //     if(number == null  && chatMasterId != "fb0593bf-bee9-4350-845f-9aad236f7186"){
  //       setPref("int", custoCa, 0);
  //       newMesssageCount =  0;
  //     }else if(number != null && chatMasterId != "fb0593bf-bee9-4350-845f-9aad236f7186"){
  //       newMesssageCount =  await getPref("int", custoCa);
  //     }
  //   }
  // }

  @override
  Widget build(BuildContext context) {
    return Slidable(
      actionPane: SlidableDrawerActionPane(),
      actionExtentRatio: 0.25,
      child: Padding(
        padding: EdgeInsets.all(mediaQuery(context, 'h', 30)),
        child: Container(
          decoration: BoxDecoration(
            shape: BoxShape.rectangle,
            borderRadius: BorderRadius.all(Radius.circular(8.0)),
            color: Colors.white,
            boxShadow: [
              BoxShadow(
                color: Colors.black26,
                blurRadius: 10.0,
                spreadRadius: 2,
                offset: Offset(0.0, 5.0),
              )
            ],
          ),
          width: mediaQuery(context, 'w', 1000),
          height: mediaQuery(context, 'w', 200),
          child: ListTile(
            leading: Container(
              decoration: BoxDecoration(
                border: Border(
                  right: BorderSide(
                    color: Colors.black,
                  ),
                ),
              ),
              child: Image.asset(
                image,
                height: mediaQuery(context, 'h', 150),
                width: mediaQuery(context, 'w', 150),
              ),
            ),
            title: Container(
              alignment: Alignment.topLeft,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    id ?? "",
                    style: TextStyle(
                      fontSize: mediaQuery(context, 'w', 40),
                      fontWeight: FontWeight.bold,
                      color: Colors.black,
                    ),
                  ),
                  Text(
                    name ?? "",
                    style: TextStyle(
                      fontSize: mediaQuery(context, 'w', 25),
                      color: Colors.black,
                    ),
                    // overflow: TextOverflow.ellipsis,
                    softWrap: true,
                  ),
                  Text(
                    address ?? "",
                    style: TextStyle(
                      fontSize: mediaQuery(context, 'w', 25),
                      color: Colors.black,
                    ),
                    overflow: TextOverflow.ellipsis,
                    softWrap: true,
                  ),
                ],
              ),
            ),
            trailing: Wrap(
                spacing: 10.0,
                runSpacing: 10.0,
                children: <Widget>[
                  Column(
                    mainAxisSize: MainAxisSize.max,
                    children: <Widget>[
                      Text(
                        time ?? "",
                        style: TextStyle(
                          color: Colors.black,
                          fontSize: 12,
                        ),
                      ),
                      StreamBuilder(
                        stream: FirebaseFirestore
                          .instance.collection(AppStrings.collection)
                          .doc("chat-ca-"+customerCA).snapshots(),
                        builder: (BuildContext context,  snapshot) {
                          if(!snapshot.hasData){
                            return SizedBox(width: 0,);
                          }else if(snapshot.hasError){
                            return SizedBox(width: 0,);
                          } else {
                            var number = snapshot.data["running_number"];
                            int calc = 0;
                            calc = NotificationCount.calcNoti(customerCA, number);
                            if(calc.isNegative){
                              calc = 0;
                            }
                            if(number != 0){
                              return _notifyAlert(context, calc);
                            }else{
                              return SizedBox(width: 0,);
                            }
                          }
                        },
                      ),
                    ],
                  )
                ],
              ),
            onTap: () async {
              AppUrl.chatMasterId = chatMasterId;
              AppUrl.accountId = accountId;
              AppUrl.typeAccount = typeAccount;
              AppUrl.CustomerID = customerID;
              AppUrl.CA = customerCA;
              AppUrl.chatId = chatRoomId;
              AppUrl.typeChat = typeChat;
              int calc = 0;
              int coutChat = NotificationCount.getCounts(customerCA) == null ? 0 : NotificationCount.getCounts(customerCA);
              bool checkChat = await checkPref("chat");
              if(checkChat){
                var chat = NotificationCount.getCounts("chat");
                print("chat : " +chat.toString());
                print("coutChat : " +coutChat.toString());
                calc = chat - coutChat;
                print("calc : " +calc.toString());
                if(calc.isNegative){
                  calc = 0;
                }
              }else{
                setPref("int", "chat", 0);
              }

              Provider.of<NotificationCount>(context,listen: false).addChatCount(calc);
              setPref('int', "chat", calc);
              setPref("int", customerCA, 0);
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => ChatPages(
                    masterId: chatMasterId,
                    customerId : customerID,
                    roomName: name,
                    id: "32FB032C-7F6C-4BD2-ACB7-54817EDB8CEC",
                    roomType: "individual"
                  ),
                ),
              );
            },
          ),
        ),
      ),
    );
  }

  Widget _notifyAlert(context, int numberCount){
    return numberCount != 0 ? 
    Container(
      margin: EdgeInsets.only(
        top: mediaQuery(context, 'w', 5.0),
      ),
      height: mediaQuery(context, 'h', 80),
      width: mediaQuery(context, 'w', 90),
      decoration: BoxDecoration(
        color: Colors.red,
        borderRadius: BorderRadius.all(
          Radius.circular(25.0),
        ),
      ),
        child: Center(
          child: Text(
            '$numberCount',
            style: TextStyle(
              fontSize: mediaQuery(context, 'h', 45),
              color: Colors.white,
            ),
          ),
        ),
    ): SizedBox(width: 0,);
  }
}
