import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';

import 'package:get/get.dart';
import 'package:mwf_app/service/notification_firebase.dart';
import 'package:mwf_app/home.dart';
import 'package:mwf_app/service/url.dart';
import 'package:mwf_app/service/pref.dart';
import 'package:mwf_app/service/assets.dart';
import 'package:mwf_app/service/color.dart';
import 'package:mwf_app/service/header.dart';
import 'package:mwf_app/service/loader.dart';
import 'package:mwf_app/service/screen.dart';
import 'package:mwf_app/service/strings.dart';
import 'package:need_resume/need_resume.dart';
import 'package:mwf_app/service/fontsize.dart';
import 'package:mwf_app/model/chat_master.dart';
import 'package:mwf_app/set7/chat_list_group.dart';
import 'package:mwf_app/set7/chat_list_view_item.dart';
import 'package:mwf_app/service/notification_count.dart';
import 'package:firebase_messaging/firebase_messaging.dart';

class Chathome extends StatefulWidget {
  static setValue(ca){
    _ChathomeState.setCa(ca);
  }
  @override
  _ChathomeState createState() => _ChathomeState();
}

class _ChathomeState extends ResumableState<Chathome> {
  static String chatmaster = "";
  static String customerCA = "";
  static int counter = 0;
  List<dynamic> dataCA = [];
  @override
  void initState(){
    ManageNotify.initNotify();
    initFirebaseMessaging();
    super.initState();
    loadData();
    var g = NotificationCount.getCounts("fb0593bf-bee9-4350-845f-9aad236f7186");
    print("ggg :  " + g.toString());
    var a = NotificationCount.getCounts("fb0593bf-bee9-4350-845f-9aad236f7186_store");
    print("aaa :  " + a.toString());
    // setPref('int','chat',0);
  }

  static setCa(ca){
    customerCA = ca;
  }

   void initFirebaseMessaging() async {
    FirebaseMessaging firebaseMessaging = FirebaseMessaging();
    await ManageNotify.subScribesNotifyTopic(firebaseMessaging);
    // firebaseMessaging.subscribeToTopic("pea_notification").whenComplete(()=> print("Everything of pea_notification Okay.."));
    // firebaseMessaging.subscribeToTopic("fb0593bf-bee9-4350-845f-9aad236f7186").whenComplete(()=> print("Everything of group Okay.."));
    firebaseMessaging.configure(
      onBackgroundMessage: backgrounfHandler,
      onMessage: (Map<String, dynamic> message) async {
        if (message.isNotEmpty) {
          setState(() {
            print("::  " + message.toString());
            if(message['data']['accountId'] != AppUrl.userID ){
              handleCountChat(message);
              ManageNotify.showNotify(message);
            }
          });
        } else {
          message.clear();
        }
      },
      onLaunch: (Map<String, dynamic> message) async {
        bool status = NotificationCount.getPrefBool("isLaunch") == null ? true : NotificationCount.getPrefBool("isLaunch");
        if(status == false){
          if(message.containsKey("data")){
            await ManageNotify.manageOnLaunch(message);
          }
        }
      },
      onResume: (Map<String, dynamic> message) async {
        if(message.containsKey("data")){
          await NotificationCount.getCount();            
          FirebaseNotificationModel datas = FirebaseNotificationModel.fromJson(message['data']);
          var receivedData = await ManageNotify.getDataNoti(datas);
          FirebaseNotificationModel data = FirebaseNotificationModel.fromJson(jsonDecode(receivedData));
          await ManageNotify.selectNotifyOnResume(data);
          message.clear();
        }
      },
    );

    firebaseMessaging.requestNotificationPermissions(
        const IosNotificationSettings(sound: true, badge: true, alert: true));

    firebaseMessaging.onIosSettingsRegistered
        .listen((IosNotificationSettings settings) {
      print("Settings registered: $settings");
    });

    firebaseMessaging.getToken().then((String token) {
      assert(token != null);
      print("Token : $token");
    });
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state){
    if(state == AppLifecycleState.inactive){
      setPref('bool', "isAppOpen", false);
      setPref('bool', "isLaunch", false);
    }
    print(state);
  }

  @override
  void onResume() {
    loadData();
  }

  loadData() async {
    AppLoader.show();
    try {
      final list = await ChatMaster.getData();
      setState(() {
        ChatMaster.data.clear();
        ChatMaster.dataGroup.clear();
        if (list != null) {
          list.forEach((v) async {
            final ChatMaster chatMasterList = ChatMaster.fromJson(v);
            if(chatMasterList.typeChat != "0325D48B-0E85-4FCE-854A-88328D417426"){
              counter = await getPref('int', chatMasterList.ca);
              var datas = {
                "CA" : chatMasterList.ca,
                "value" : counter
              };
              dataCA.insert(0,datas);
              //ChatListViewItem.getNumber(chatMasterList.ca, chatMasterList.chatMasterId);
              ChatMaster.data.add(chatMasterList); // loop เก็บข้อมูล
            }else{
              //ChatListGroup.getCountGroup(chatMasterList.chatMasterId);
              ChatMaster.dataGroup.add(chatMasterList);
            }
          });
        }
      });
      //await Future.delayed(const Duration(seconds: 1));
    } catch (e) {
      print(e);
    }
    AppLoader.hide();
  }

  static handleCountChat(message) async{
      print("Handle chat");
      int count = 0;
      if(message.isNotEmpty){
        if(message.containsKey("data") && message.containsKey("notification")){
          String type = message['data']['noti_type'].toString().toLowerCase();
          if(type == "chat") {
            count +=1;
            String chatMaster = message['data']['chatMasterId'].toString().toLowerCase();
            String isChatGroup = message['data']['isGroupChat'];
            customerCA = message['data']['CA'];
            NotificationCount.setCount("chat");
            chatmaster = chatMaster;
            if(isChatGroup == "true"){
              var dataGroup;
              dataGroup = await getPref("int" , chatMaster);
              if(dataGroup != null){
                //setPref("int", chatMaster, dataGroup+count);
                
              }else if(dataGroup == null){
                setPref("int", chatMaster, count);
              }
              ChatListGroup.getCountGroup(chatMaster);
            }else if(isChatGroup == "false"){
              var data;
              data = NotificationCount.getCounts(customerCA);

              if(data != null){
                print("1 isChatGroup == false");
                //setPref("int", customerCA, data+count);
                counter = await getPref('int', customerCA);
              }else if(data == null){
                print("2");
                setPref("int", customerCA, count);
                counter = await getPref('int', customerCA);
              }
            }
          }
        }
      }
  }
  
  @override
  Widget build(BuildContext context) {
    Header.currentPage = "chat";
    Header.routes = HomePage();
    double _width = MediaQuery.of(context).size.width;
    return Material(
      color: AppColors.bgColor,
      child: WillPopScope(
        onWillPop: () async {
          Get.offAll(Header.routes);
          return false;
        },
        child: Stack(
          children: <Widget>[
            Header.header2ListPage(context),
            Header.mainMenu(context),
            Row(
              children: <Widget>[
                Container(
                  width: _width,
                  height: mediaQuery(context, 'h', 600),
                  alignment: Alignment.center,
                  margin: EdgeInsets.only(top: mediaQuery(context, 'h', 360)),
                  child: Column(
                    children: <Widget>[
                      Text(
                        'ห้องสนทนา',
                        style: TextStyle(
                          fontSize:
                              mediaQuery(context, 'w', AppFontSize.headText),
                          color: AppColors.color_gold,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            Column(
              children: [
                Container(
                  height: mediaQuery(context, 'h', 1801),
                  margin: EdgeInsets.only(
                    top: mediaQuery(context, 'h', 460),
                    bottom: mediaQuery(context, 'h', 175),
                  ),
                  child: SingleChildScrollView(
                    child: Column(
                      children: <Widget>[
                        _chatGroupList(),
                        _chat1Per1List(),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  getNumber(index, ca) {
    int count=0;
    for(var i=0; i < dataCA.length; i++){
      if(dataCA[i]['CA'] == ca){
        count = dataCA[i]['value'];
      }
    }
    return count;
  }

  _chat1Per1List() {
    if (AppStrings.typeChatSingle.isEmpty && ChatMaster.data.length > 1) {
      AppStrings.typeChatSingle = ChatMaster.data[1].typeChat ?? "";
    }
    return Container(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          Container(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Container(
                  padding: EdgeInsets.only(left: mediaQuery(context, 'h', 40)),
                  alignment: Alignment.topLeft,
                  child: Container(
                    child: Text(
                      'ห้องสนทนาลูกค้า',
                      style: TextStyle(
                        fontSize: mediaQuery(context, 'w', 35),
                        color: AppColors.Black,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          Column(
            children: [
              ListView.builder(
                itemCount: ChatMaster.data.length,
                shrinkWrap: true,
                itemBuilder: (BuildContext context, index) => makeElement(index)
              )
            ],
            // children:  List.generate(
            //   ChatMaster.data.isNotEmpty ? ChatMaster.data.length  : 0,
            //   (index) {
            //     return ChatListViewItem(
            //       chatRoomId: ChatMaster.data[index].id,
            //       hasUnreadMessage: true,
            //       image: AppAssets.iconschat ?? '',
            //       address: ChatMaster.data[index].customerAddress ?? '',
            //       id: ChatMaster.data[index].ca ?? '',
            //       name: ChatMaster.data[index].customerName ?? '',
            //       newCount: 1,
            //       // newCount: 
            //       //   ChatMaster.data[index].ca == customerCA ? counter : getNumber(index, ChatMaster.data[index].ca),
            //       time: ChatMaster.data[index].strTime ?? '',
            //       chatMasterId: ChatMaster.data.isNotEmpty
            //           ? ChatMaster.data[index].chatMasterId ?? ''
            //           : '',
            //       typeAccount: ChatMaster.data[index].typeAccount,
            //       typeChat: ChatMaster.data[index].typeChat,
            //       accountId: ChatMaster.data[index].accountId ?? '',
            //       customerID: ChatMaster.data[index].customerId ?? '',
            //       customerCA: ChatMaster.data[index].ca ?? '',
            //       inCa: customerCA,
            //     );
            //   },
            // ),
          ),
        ],
      ),
    );
  }

  _chatGroupList() {
    double _width = MediaQuery.of(context).size.width;
    return Container(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          Container(
            alignment: Alignment.topLeft,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Container(
                  padding: EdgeInsets.only(left: mediaQuery(context, 'h', 40)),
                  alignment: Alignment.topLeft,
                  child: Text(
                    'ห้องรวม',
                    style: TextStyle(
                      fontSize: mediaQuery(context, 'w', 35),
                      color: AppColors.Black,
                    ),
                  ),
                ),
              ],
            ),
          ),
          Container(
            width: _width,
            child: Column(
              children: [
                Container(
                  child: Row(
                    children: <Widget>[
                      Container(
                        width: _width,
                        alignment: Alignment.center,
                        child: Column(
                          children: <Widget>[
                            Container(
                              child: ChatListGroup(
                                time: '',
                                name: 'ห้องสนทนารวม',
                                hasUnreadMessage: true,
                                accountId: 'c5388c95-d54a-4ec3-b76b-9979ac0f40e0',
                                typeAccount: '2ae2539c-4a49-4578-9bd3-136eab70ddfc',
                                chatMasterId: "fb0593bf-bee9-4350-845f-9aad236f7186",
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                )
              ]
            ),
          ),
        ],
      ),
    );
  }

  Widget makeElement(int index) {
    if(index >= ChatMaster.data.length){
      return null;
    }
    
    //Good way 
    return Column(      
      children : [
        ChatListViewItem(
          chatRoomId: ChatMaster.data[index].id,
          hasUnreadMessage: true,
          image: AppAssets.iconschat ?? '',
          address: ChatMaster.data[index].customerAddress ?? '',
          id: ChatMaster.data[index].ca ?? '',
          name: ChatMaster.data[index].customerName ?? '',
          newCount: 1,
          // newCount: 
          //   ChatMaster.data[index].ca == customerCA ? counter : getNumber(index, ChatMaster.data[index].ca),
          time: ChatMaster.data[index].strTime ?? '',
          chatMasterId: ChatMaster.data.isNotEmpty
              ? ChatMaster.data[index].chatMasterId ?? ''
              : '',
          typeAccount: ChatMaster.data[index].typeAccount,
          typeChat: ChatMaster.data[index].typeChat,
          accountId: ChatMaster.data[index].accountId ?? '',
          customerID: ChatMaster.data[index].customerId ?? '',
          customerCA: ChatMaster.data[index].ca ?? '',
          inCa: customerCA,
        )
      ],
    );
  }
}
