import 'dart:async';
import 'dart:io';

import 'package:fcs/data/services/services.dart';
import 'package:fcs/domain/entities/user.dart';
import 'package:fcs/helpers/theme.dart';
import 'package:fcs/localization/transalation.dart';
import 'package:fcs/pages/box/box_list.dart';
import 'package:fcs/pages/chat/message_detail.dart';
import 'package:fcs/pages/chat/model/message_model.dart';
import 'package:fcs/pages/customer/customer_list.dart';
import 'package:fcs/pages/customer/model/customer_model.dart';
import 'package:fcs/pages/delivery/delivery_list.dart';
import 'package:fcs/pages/discount/discount_list.dart';
import 'package:fcs/pages/faq/faq_list_page.dart';
import 'package:fcs/pages/fcs_shipment/fcs_shipment_list.dart';
import 'package:fcs/pages/invoice/invoce_list.dart';
import 'package:fcs/pages/main/model/language_model.dart';
import 'package:fcs/pages/main/model/main_model.dart';
import 'package:fcs/pages/package/package_list.dart';
import 'package:fcs/pages/processing/processing_list.dart';
import 'package:fcs/pages/rates/shipment_rates.dart';
import 'package:fcs/pages/receiving/receiving_list.dart';
import 'package:fcs/pages/shipment/shipment_list.dart';
import 'package:fcs/pages/staff/staff_list.dart';
import 'package:fcs/pages/widgets/task_button.dart';
import 'package:fcs/pages/widgets/badge.dart';
import 'package:fcs/pages/widgets/bottom_up_page_route.dart';
import 'package:fcs/pages/widgets/bottom_widgets.dart';
import 'package:fcs/pages/widgets/right_left_page_rout.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_icons/flutter_icons.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:intl/intl.dart';
import 'package:logging/logging.dart';
import 'package:provider/provider.dart';

import '../profile/profile_page.dart';
import '../signin/signin_page.dart';
import '../widgets/banner.dart';
import '../widgets/offline_redirect.dart';

final msgLog = Logger('backgroundMessageHandler');

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final log = Logger('_HomePageState');
  bool login = false;
  bool customer = true;
  List<bool> isSelected = [true, false];
  static FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();

  @override
  void initState() {
    super.initState();
    MainModel mainModel = Provider.of<MainModel>(context, listen: false);

    Services.instance.messagingService.init(
        (message) {
          print("Message from FCM:$message");
          _showNotification(message);
        },
        onLaunch: (m) => _showNotiContent(m),
        onResume: (m) => _showNotiContent(m),
        onSetupComplete: (token) {
          mainModel.setMessaginToken = token;
        });
    _initLocalNotifications();
  }

  String notiUserID, notiUserName;
  _showNotiContent(Map<String, dynamic> message) {
    try {
      Map<String, dynamic> map = Map<String, dynamic>.from(message["data"]);
      notiUserID = map['user_id'];
      notiUserName = map['user_name'];
      _startNotiTimer();
      print("Notification:$map");
    } catch (e) {
      print("Error:$e");
    }
  }

  _startNotiTimer() async {
    var _duration = new Duration(milliseconds: 500);
    new Timer.periodic(_duration, (t) => displayNoti(t));
  }

  void displayNoti(Timer timer) async {
    MainModel mainModel = Provider.of<MainModel>(context, listen: false);
    if (mainModel.isLogin()) {
      timer.cancel();
      bool isCustomer = mainModel.isCustomer();
      String receiverID = isCustomer ? mainModel.user.id : notiUserID;
      String receiverName = isCustomer ? mainModel.user.name : notiUserName;
      MessageModel messageModel =
          Provider.of<MessageModel>(context, listen: false);
      messageModel.initQuery(receiverID);
      User user = mainModel.user;
      if (!isCustomer) {
        CustomerModel customerModel =
            Provider.of<CustomerModel>(context, listen: false);
        user = await customerModel.getUser(receiverID);
      }
      Navigator.push(
          context,
          MaterialPageRoute(
              builder: (context) => MessageDetail(
                    messageModel: messageModel,
                    receiverID: receiverID,
                    receiverName: receiverName,
                  ))).then((value) {
        if (user.userUnseenCount > 0) {
          messageModel.seenMessages(user.id, true);
        }
      });
      if (user.userUnseenCount > 0) {
        messageModel.seenMessages(user.id, true);
      }
    }
  }

  _initLocalNotifications() {
    var initializationSettingsAndroid =
        new AndroidInitializationSettings('@mipmap/ic_launcher');
    var initializationSettingsIOS = new IOSInitializationSettings();
    var initializationSettings = new InitializationSettings(
        initializationSettingsAndroid, initializationSettingsIOS);
    _flutterLocalNotificationsPlugin.initialize(initializationSettings);
  }

  static Future _showNotification(Map<String, dynamic> message) async {
    var pushTitle;
    var pushText;
    var action;

    if (Platform.isAndroid) {
      var nodeData = message['notification'];
      pushTitle = nodeData['title'];
      pushText = nodeData['body'];
      action = nodeData['action'];
    } else {
      pushTitle = message['title'];
      pushText = message['body'];
      action = message['action'];
    }
    print("AppPushs params pushTitle : $pushTitle");
    print("AppPushs params pushText : $pushText");
    print("AppPushs params pushAction : $action");

    // @formatter:off
    var platformChannelSpecificsAndroid = new AndroidNotificationDetails(
        'your channel id', 'your channel name', 'your channel description',
        playSound: true,
        enableVibration: true,
        importance: Importance.Max,
        priority: Priority.High);
    // @formatter:on
    var platformChannelSpecificsIos =
        new IOSNotificationDetails(presentSound: true);
    var platformChannelSpecifics = new NotificationDetails(
        platformChannelSpecificsAndroid, platformChannelSpecificsIos);

    new Future.delayed(Duration.zero, () {
      _flutterLocalNotificationsPlugin.show(
        0,
        pushTitle,
        pushText,
        platformChannelSpecifics,
        payload: 'No_Sound',
      );
    });
  }

  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    User user = Provider.of<MainModel>(context).user;
    if (user == null) {
      return Container();
    }
    customer = Provider.of<MainModel>(context).isCustomer();

    login = Provider.of<MainModel>(context).isLogin();
    LanguageModel languageModel = Provider.of<LanguageModel>(context);

    final faqBtn = TaskButton("faq.btn",
        icon: MaterialCommunityIcons.frequently_asked_questions,
        btnCallback: () => Navigator.of(context).push(CupertinoPageRoute(
              builder: (context) => FAQListPage(),
            )));

    final packagesBtn = TaskButton("package.btn.name",
        icon: Octicons.package,
        btnCallback: () => Navigator.of(context).push<void>(
            CupertinoPageRoute(builder: (context) => PackageList())));

    final receivingBtn = TaskButton("receiving.title",
        icon: Octicons.package,
        btnCallback: () => Navigator.of(context).push<void>(
            CupertinoPageRoute(builder: (context) => ReceivingList())));

    final processingBtn = TaskButton("processing.title",
        icon: Octicons.package,
        btnCallback: () => Navigator.of(context).push<void>(
            CupertinoPageRoute(builder: (context) => ProcessingList())));
    final boxesBtn = TaskButton("boxes.name",
        icon: MaterialCommunityIcons.package,
        btnCallback: () =>
            Navigator.of(context).push(BottomUpPageRoute(BoxList())));

    final pickUpBtn = TaskButton("shipment",
        icon: SimpleLineIcons.direction,
        btnCallback: () =>
            Navigator.of(context).push(BottomUpPageRoute(ShipmentList())));

    final shipmentCostBtn = TaskButton("rate",
        icon: FontAwesomeIcons.calculator,
        btnCallback: () =>
            Navigator.of(context).push(BottomUpPageRoute(ShipmentRates())));

    final fcsShipmentBtn = TaskButton("FCSshipment.title",
        icon: Ionicons.ios_airplane,
        btnCallback: () => Navigator.of(context).push<void>(CupertinoPageRoute(
              builder: (context) => FcsShipmentList(),
            )));

    final notiBtnOrg =
        TaskButton("message.btn", icon: Icons.message, btnCallback: () {
      MessageModel messageModel =
          Provider.of<MessageModel>(context, listen: false);
      messageModel.initQuery(user.id);
      Navigator.push(
        context,
        BottomUpPageRoute(MessageDetail(
          messageModel: messageModel,
        )),
      ).then((value) {
        if (user.userUnseenCount > 0) {
          messageModel.seenMessages(user.id, true);
        }
      });
      if (user.userUnseenCount > 0) {
        messageModel.seenMessages(user.id, true);
      }
    });
    final notiBtn = badgeCounter(notiBtnOrg, user.userUnseenCount);

    final staffBtn = TaskButton(
      "staff.title",
      icon: MaterialCommunityIcons.worker,
      btnCallback: () => Navigator.of(context).push<void>(CupertinoPageRoute(
        builder: (context) => StaffList(),
      )),
    );

    final customersBtn = TaskButton("customers.btn",
        icon: Feather.users,
        btnCallback: () => Navigator.of(context).push<void>(CupertinoPageRoute(
              builder: (context) => CustomerList(),
            )));

    final invoicesBtn = TaskButton("invoices.btn",
        icon: FontAwesomeIcons.fileInvoice,
        btnCallback: () =>
            Navigator.of(context).push(BottomUpPageRoute(InvoiceList())));

    final discountBtn = TaskButton("discount.btn",
        icon: Entypo.price_ribbon,
        btnCallback: () =>
            Navigator.of(context).push(BottomUpPageRoute(DiscountList())));

    final deliveryBtn = TaskButton("delivery.title",
        icon: MaterialCommunityIcons.truck_fast,
        btnCallback: () =>
            Navigator.of(context).push(BottomUpPageRoute(DeliverList())));

    List<Widget> widgets = [];
    widgets.add(faqBtn);
    if (user != null) {
      // true ? widgets.add(pickUpBtn) : "";
      !customer ? widgets.add(fcsShipmentBtn) : "";
      customer ? widgets.add(notiBtn) : "";
      user.hasStaffs() ? widgets.add(staffBtn) : "";
      widgets.add(shipmentCostBtn);
      user.hasPackages() ? widgets.add(packagesBtn) : "";
      user.hasPackages() ? widgets.add(receivingBtn) : "";
      user.hasPackages() ? widgets.add(processingBtn) : "";
      true ? widgets.add(boxesBtn) : "";
      true ? widgets.add(deliveryBtn) : "";
      user.hasCustomers() ? widgets.add(customersBtn) : "";
      // true ? widgets.add(invoicesBtn) : "";
      // true ? widgets.add(discountBtn) : "";
    }
    return OfflineRedirect(
      child: FlavorBanner(
        child: Scaffold(
            appBar: AppBar(
                elevation: 0,
                backgroundColor: primaryColor,
                title: ClipRRect(
                  child: Image.asset("assets/logo.jpg", height: 40),
                  borderRadius: new BorderRadius.circular(30.0),
                ),
                actions: login
                    ? <Widget>[
                        ToggleButtons(
                          children: <Widget>[
                            Image.asset(
                              'icons/flags/png/us.png',
                              package: 'country_icons',
                              fit: BoxFit.fitWidth,
                              width: 25,
                            ),
                            Image.asset(
                              'icons/flags/png/mm.png',
                              package: 'country_icons',
                              fit: BoxFit.fitWidth,
                              width: 25,
                            )
                          ],
                          onPressed: _langChange,
                          isSelected: languageModel.currentState,
                          selectedBorderColor: Colors.white24,
                        ),
                        IconButton(
                          onPressed: () {
                            Navigator.of(context)
                                .push(RightLeftPageRoute(Profile()));
                          },
                          iconSize: 30,
                          icon: Icon(Icons.account_circle),
                        ),
                      ]
                    : <Widget>[
                        ToggleButtons(
                          children: <Widget>[
                            Image.asset(
                              'icons/flags/png/us.png',
                              package: 'country_icons',
                              fit: BoxFit.fitWidth,
                              width: 25,
                            ),
                            Image.asset(
                              'icons/flags/png/mm.png',
                              package: 'country_icons',
                              fit: BoxFit.fitWidth,
                              width: 25,
                            )
                          ],
                          onPressed: _langChange,
                          isSelected: languageModel.currentState,
                        ),
                        FlatButton(
                          onPressed: () {
                            Navigator.of(context)
                                .push(BottomUpPageRoute(SigninPage()));
                          },
                          child: Text(
                            "Sign In",
                            style: siginButtonStyle,
                          ),
                        ),
                      ]),
            body: Container(
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [
                      Color(0xd0272262),
                      Color(0xfa272262),
                    ],
                  ),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Expanded(
                      child: ListView(children: [
                        Wrap(
                          alignment: WrapAlignment.center,
                          children: widgets,
                        ),
                      ]),
                    ),
                    BottomWidgets(),
                  ],
                ))),
      ),
    );
  }

  _langChange(index) {
    var languageModel = Provider.of<LanguageModel>(context, listen: false);
    languageModel.saveLanguage(Translation().supportedLanguages[index]);
    setState(() {
      isSelected.asMap().forEach((i, e) {
        isSelected[i] = false;
      });
      isSelected[index] = !isSelected[index];
    });
  }

  // Widget _buildBtn(String title, {IconData icon, BtnCallback btnCallback}) {
  //   return TaskButton(titleKey: title, icon: icon, btnCallback: btnCallback);
  // }
}
