import 'package:auto_size_text/auto_size_text.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:peasmartcare/constraints/app_data.dart';
import 'package:peasmartcare/constraints/image_asset.dart';
import 'package:peasmartcare/pages/activity/activity.dart';
import 'package:peasmartcare/pages/additional_service/additional_service.dart';
import 'package:peasmartcare/pages/chat_room/chat_room.dart';
import 'package:peasmartcare/pages/coordinator/coordinator.dart';
import 'package:peasmartcare/pages/electricity_location/electricity_location.dart';
import 'package:peasmartcare/pages/electricity_statistic/electricity_statistic.dart';
import 'package:peasmartcare/pages/feedback/feedback.dart';
import 'package:peasmartcare/pages/history_bill/history_bill.dart';
import 'package:peasmartcare/pages/news/news.dart';
import 'package:peasmartcare/pages/questionnaire/questionnaire.dart';
import 'package:peasmartcare/pages/report_incident/report_incident.dart';
import 'package:peasmartcare/pages/survey/survey_group.dart';
import 'package:peasmartcare/pages/timeline/timeline.dart';
import 'package:peasmartcare/utils/clear_count_notification_util.dart';
import 'package:peasmartcare/utils/share_data_util.dart';
import 'package:peasmartcare/widgets/empty_box.dart';

class HomeMenu extends StatefulWidget {
  @override
  _HomeMenuState createState() => _HomeMenuState();
}

class _HomeMenuState extends State<HomeMenu> {
  int _selectedMenuIndex = -1;
  int _newsCount = 0;
  int _timelineCount = 0;
  int _activityCount = 0;
  int _additionalServiceCount = 0;
  int _reportIncidentCount = 0;

  @override
  Future<void> initState() {
    super.initState();
  }

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

    return Column(
      children: <Widget>[
        Row(
          children: <Widget>[
            _buildMenu(
              context,
              0,
              "สถิติการใช้ไฟฟ้า",
              image: ImageAsset.electricityStatisticImg,
              pageRoute: ElectricityStatisticPage(),
            ),
            _buildMenu(
              context,
              1,
              "ประวัติการชำระเงินค่าไฟฟ้า",
              image: ImageAsset.historyBillImg,
              pageRoute: HistoryBillPage(),
            ),
            _buildMenu(
              context,
              2,
              "ร้องเรียน ข้อเสนอแนะ",
              image: ImageAsset.complaintImg,
              pageRoute: FeedbackPage(),
            ),
          ],
        ),
        Row(
          children: <Widget>[
            _buildMenu(
              context,
              3,
              "แจ้งเหตุไฟฟ้าขัดข้อง และดูแผนดับไฟฟ้า",
              image: ImageAsset.reportIncidentImg,
              fontSize: deviceSize.width > 500 ? null : 12,
              pageRoute: ReportIncidentPage(),
              badgeCountChild: StreamBuilder(
                  stream: FirebaseFirestore.instance
                      .collection(AppData.cloudFilestoreCollection)
                      .doc(AppData.cloudFilestoreDocumentElectricproblem)
                      .snapshots(),
                  builder: (context, snapshot) {
                    if (!snapshot.hasData) {
                      return EmptyBox(heightFactor: 0);
                    } else {
                      int runningNumber = snapshot.data["running_number"];
                      _reportIncidentCount =
                          ShareDataUtil.getReportIncidentNotiCount(
                              runningNumber);

                      return _badgeCount(_reportIncidentCount);
                    }
                  }),
            ),
            _buildMenu(
              context,
              4,
              "ห้องสนทนา",
              image: ImageAsset.chatRoomImg,
              pageRoute: ChatRoomPage(),
              badgeCountChild: StreamBuilder(
                  stream: FirebaseFirestore.instance
                      .collection(AppData.cloudFilestoreCollection)
                      .snapshots(),
                  builder: (BuildContext context,
                      AsyncSnapshot<QuerySnapshot> snapshot) {
                    if (!snapshot.hasData) {
                      return EmptyBox(heightFactor: 0);
                    } else {
                      print(ShareDataUtil.getAllChatMasterId().length);
                      int chatCount = 0;

                      snapshot.data.docs.map((doc) {
                        ShareDataUtil.getAllChatMasterId().map((masterId) {
                          // dynamic data = snapshot.data.docs.where((item) => item.data().containsValue(masterId)).toList();

                          // print(data);

                          if (doc.id == "chat-masterid-$masterId") {
                            chatCount = chatCount +
                                ShareDataUtil.getChatNotiCount(
                                    masterId, doc.data()["running_number"]);
                          }
                        }).toList();
                      }).toList();

                      // snapshot.data.docs
                      //     .map((doc) => {
                      //           // print(doc["name"]),
                      //           print(doc.data()["running_number"])
                      //         })
                      //     .toList();
                      // print("**---***----");

                      return _badgeCount(chatCount);
                    }
                  }),
              // badgeCountChild: BlocBuilder<ChatMenuBadgeCountBloc, ChatMenuBadgeCountState>(
              //   builder: (context, state) {
              //     if (state is ChatMenuBadgeCountLoaded) {
              //       return _badgeCount(state.result);
              //     }

              //     return EmptyBox(heightFactor: 0);
              //   },
              // ),
            ),
            _buildMenu(
              context,
              5,
              "ขอใช้บริการเสริม",
              image: ImageAsset.additionalServiceImg,
              pageRoute: AdditionalServicePage(),
              badgeCountChild: StreamBuilder(
                  stream: FirebaseFirestore.instance
                      .collection(AppData.cloudFilestoreCollection)
                      .doc(AppData.cloudFilestoreDocumentPackagerequest)
                      .snapshots(),
                  builder: (context, snapshot) {
                    if (!snapshot.hasData) {
                      return EmptyBox(heightFactor: 0);
                    } else {
                      int runningNumber = snapshot.data["running_number"];
                      _additionalServiceCount =
                          ShareDataUtil.getAdditionalServiceNotiCount(
                              runningNumber);

                      return _badgeCount(_additionalServiceCount);
                    }
                  }),
            ),
          ],
        ),
        Row(
          children: <Widget>[
            _buildMenu(
              context,
              6,
              "กิจกรรมที่เข้าร่วม",
              image: ImageAsset.activityImg,
              pageRoute: ActivityPage(),
              badgeCountChild: StreamBuilder(
                  stream: FirebaseFirestore.instance
                      .collection(AppData.cloudFilestoreCollection)
                      .doc(AppData.cloudFilestoreDocumentActivity)
                      .snapshots(),
                  builder: (context, snapshot) {
                    if (!snapshot.hasData) {
                      return EmptyBox(heightFactor: 0);
                    } else {
                      int runningNumber = snapshot.data["running_number"];
                      _activityCount =
                          ShareDataUtil.getActivityNotiCount(runningNumber);

                      return _badgeCount(_activityCount);
                    }
                  }),
            ),
            _buildMenu(
              context,
              7,
              "ระบุที่ตั้งสำนักงาน",
              image: ImageAsset.contactLocationImg,
              pageRoute: ElectricityLocationPage(),
            ),
            _buildMenu(
              context,
              8,
              "กำหนดผู้ประสานงาน",
              image: ImageAsset.coordinatorImg,
              pageRoute: CoordinatorPage(),
            ),
          ],
        ),
        Row(
          children: <Widget>[
            _buildMenu(
              context,
              9,
              "ตอบแบบสอบถาม",
              image: ImageAsset.questionnaireImg,
              pageRoute: QuestionnairePage(),
            ),
            _buildMenu(
              context,
              10,
              "บันทึกแบบสำรวจข้อมูล",
              image: ImageAsset.surveyImg,
              pageRoute: SurveyGroupPage(),
            ),
            _buildMenu(
              context,
              11,
              "Timeline",
              image: ImageAsset.timelineImg,
              pageRoute: TimelinePage(),
              badgeCountChild: StreamBuilder(
                  stream: FirebaseFirestore.instance
                      .collection(AppData.cloudFilestoreCollection)
                      .doc(AppData.cloudFilestoreDocumentTimeline)
                      .snapshots(),
                  builder: (context, snapshot) {
                    if (!snapshot.hasData) {
                      return EmptyBox(heightFactor: 0);
                    } else {
                      int runningNumber = snapshot.data["running_number"];
                      _timelineCount =
                          ShareDataUtil.getTimelineNotiCount(runningNumber);

                      return _badgeCount(_timelineCount);
                    }
                  }),
            ),
          ],
        ),
        Row(
          children: <Widget>[
            _buildMenu(
              context,
              12,
              "ข่าวประชาสัมพันธ์",
              image: ImageAsset.newsImg,
              pageRoute: NewsPage(),
              badgeCountChild: StreamBuilder(
                  stream: FirebaseFirestore.instance
                      .collection(AppData.cloudFilestoreCollection)
                      .doc(AppData.cloudFilestoreDocumentNews)
                      .snapshots(),
                  builder: (context, snapshot) {
                    if (!snapshot.hasData) {
                      return EmptyBox(heightFactor: 0);
                    } else {
                      int runningNumber = snapshot.data["running_number"];
                      _newsCount =
                          ShareDataUtil.getNewsNotiCount(runningNumber);

                      return _badgeCount(_newsCount);
                    }
                  }),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildMenu(
    BuildContext context,
    int index,
    String heading, {
    String image,
    IconData icon,
    Color color,
    Color backgroundColor,
    double fontSize,
    Widget pageRoute,
    Widget badgeCountChild,
  }) {
    Size deviceSize = MediaQuery.of(context).size;

    return GestureDetector(
      onTap: () {
        setState(() {
          _selectedMenuIndex = index;
        });
        if (pageRoute != null) {
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => pageRoute),
          );
        }
      },
      child: Stack(
        children: [
          Container(
            height: 130,
            padding: EdgeInsets.all(5),
            width: deviceSize.width / 3,
            child: Card(
              elevation: 3,
              shape: RoundedRectangleBorder(
                side: BorderSide(
                  width: 2,
                  style: BorderStyle.solid,
                  color: _selectedMenuIndex == index
                      ? color != null ? color : Color(AppData.purpleColor)
                      : Colors.white,
                ),
                borderRadius: BorderRadius.circular(10),
              ),
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    Padding(
                      padding: const EdgeInsets.fromLTRB(8, 8, 8, 0),
                      child: Stack(
                        alignment: Alignment(0, 0),
                        children: <Widget>[
                          Container(
                            width: 43,
                            height: 43,
                            decoration: BoxDecoration(
                                color: backgroundColor != null
                                    ? backgroundColor
                                    : Colors.orange[50],
                                borderRadius: BorderRadius.circular(15)),
                          ),
                          image != null
                              ? Image.asset(image, height: 35)
                              : Icon(
                                  icon,
                                  color: color,
                                ),
                          SizedBox(
                            height: 4,
                          )
                        ],
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.all(5),
                      child: AutoSizeText(
                        heading,
                        textAlign: TextAlign.center,
                        maxLines: 2,
                        minFontSize: 8,
                        style: TextStyle(
                          color: Color(AppData.greyColor),
                          fontSize: fontSize != null ? fontSize : 14,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          (badgeCountChild != null)
              ? badgeCountChild
              : EmptyBox(heightFactor: 0),
        ],
      ),
    );
  }

  Widget _badgeCount(int count) {
    TextStyle badgeCountStyle = TextStyle(color: Colors.white, fontSize: 15);

    bool isNewRegister = ShareDataUtil.getNewRegister();
    // print("---------------------------");
    // print(isNewRegister);
    // print("---------------------------");

    if (isNewRegister) count = 0;

    return (count > 0)
        ? Positioned(
            top: 0,
            right: 0,
            child: Container(
              padding: EdgeInsets.all(1),
              decoration: BoxDecoration(
                color: Colors.red,
                borderRadius: BorderRadius.circular(50),
              ),
              constraints: BoxConstraints(
                minWidth: 30,
                minHeight: 30,
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    count <= 99 ? count.toString() : "99+",
                    style: badgeCountStyle,
                    textAlign: TextAlign.center,
                  ),
                ],
              ),
            ),
          )
        : EmptyBox(heightFactor: 0);
  }

  // Stream<int> _delayBadgeCount = (() async* {
  //   await Future<void>.delayed(Duration(microseconds: 100));
  //   yield 1;
  // })();

  // Widget _badgeCount(int count) {
  //   TextStyle badgeCountStyle = TextStyle(color: Colors.white, fontSize: 15);

  //   return (count > 0)
  //       ? StreamBuilder<int>(
  //           stream: _delayBadgeCount,
  //           builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
  //             if (snapshot.hasData) {
  //               return Positioned(
  //                 top: 0,
  //                 right: 0,
  //                 child: Container(
  //                   padding: EdgeInsets.all(1),
  //                   decoration: BoxDecoration(
  //                     color: Colors.red,
  //                     borderRadius: BorderRadius.circular(50),
  //                   ),
  //                   constraints: BoxConstraints(
  //                     minWidth: 30,
  //                     minHeight: 30,
  //                   ),
  //                   child: Column(
  //                     mainAxisAlignment: MainAxisAlignment.center,
  //                     children: [
  //                       Text(
  //                         count <= 99 ? count.toString() : "99+",
  //                         style: badgeCountStyle,
  //                         textAlign: TextAlign.center,
  //                       ),
  //                     ],
  //                   ),
  //                 ),
  //               );
  //             } else {
  //               return Container();
  //             }
  //           })
  //       : EmptyBox(heightFactor: 0);
  // }
}
