import 'package:echo_app/enums/global-errors.dart';
import 'package:echo_app/screens/my_order/my_order.page.dart';
import 'package:echo_app/screens/notifications/widgets/notification-list-item.dart';
import 'package:echo_app/screens/order_summery/order_summery.page.dart';
import 'package:echo_app/screens/tap_page/tap.page.dart';
import 'package:echo_app/services/notification.service.dart';
import 'package:echo_app/services/order.service.dart';
import 'package:echo_app/shared/core.session.dart';
import 'package:echo_app/widgets/video-player.widget.dart';
import 'package:echo_app/widgets/view_image.widget.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:echo_app/models/time-ago/time-ago.dart' as timeago;

import '../../theme/variables.dart';

class NotificationPage extends StatefulWidget {
  // const NotificationPage({Key? key}) : super(key: key);

  @override
  _NotificationPageState createState() => _NotificationPageState();
}

class _NotificationPageState extends State<NotificationPage> {
  NotificationsService _notificationsService = new NotificationsService();
  OrderService _orderService = new OrderService();
  // CoreSession _coreSession = new CoreSession();
  var _notificationsList = [];
  var textStyle = TextStyle(fontSize: 16);
  var textStyleToDate = TextStyle(fontSize: 16, color: Colors.grey);
  DateTime deliveryDate = new DateTime(
      DateTime.now().year, DateTime.now().month, DateTime.now().day);

  initState() {
    populateNotificationList();
    FirebaseMessaging.onMessage.listen((message) {
      print('Foreground FirebaseMessaging.onMessage.listen');
      setState(() {
        _notificationsList = [];
        populateNotificationList();
      });
    });
    super.initState();
  }

  @override
  dispose() {
    print('disposedisposedisposedisposedisposedisposedisposedisposedispose');
    FirebaseMessaging.onMessage.listen((message) {
       
    });
    super.dispose();
  }

  Future<dynamic> populateNotificationList() async {
    EasyLoading.show(status: 'loading'.tr);
    var response = await _notificationsService.getNotificationList();
    EasyLoading.dismiss();
    if (response['status'] == GlobalErrors.Success.index) {
      setState(() {
        _notificationsList = response['data'];
        CoreSession.newNotificationCount = 0;
        TapPage.enteredValue.value = CoreSession.newNotificationCount;
        // print(_notificationsList);
      });
    } else {
      EasyLoading.showError('error'.tr);
    }
  }

  void getOrderDetailsForView(index) async {
    await getOrderDetailsForViewAPI(index);
  }

  Future<dynamic> getOrderDetailsForViewAPI(index) async {
    EasyLoading.show(status: 'loading'.tr);
    var response = await _orderService
        .getOrderDetailsForView(_notificationsList[index]['orderId']);
    EasyLoading.dismiss();
    if (response['status'] == GlobalErrors.Success.index) {
      setState(() {
        var soldItems = response['data']['soldItems'];
        var promotedItems = response['data']['promotedItems'];
        var summaryDataList = [
          {
            'netTotal': response['data']['netTotal'],
            'grossTotal': response['data']['grossTotal'],
            'calculatedTotalTax': response['data']['taxTotal'],
            'calculatedTotalDiscount': response['data']['discountTotal'],
            'calculatedDiscountTotalBeforFirstUserDiscount': response['data']
                ['discountTotal']
          }
        ];

        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => OrderSummeryPage(
              true,
              _notificationsList[index]['orderStatusId'] == 9 ? true : false,
              summaryDataList,
              soldItems,
              [], //this.achivements
              promotedItems,
              () {}, this.deliveryDate, "", 0
            ),
          ),
        );
      });
    } else {
      EasyLoading.showError('error'.tr);
    }
  }

  void viewNotificationImage(notification) {
    Navigator.push(
      context,
      MaterialPageRoute(
          builder: (context) => ViewImageWidget(
              CoreSession.notificationImagePath + notification['imageName'],
              '')),
    );

  }

  void viewNotificationVideo(notification) {
    Navigator.push(
      context,
      MaterialPageRoute(
          builder: (context) => VideoPlayerScreen(
              CoreSession.notificationVideoPath + notification['videoName'])),
    );
  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Scaffold(
      appBar: AppBar(
         backgroundColor: Colors.white,
          title: Row(
            children: [
              IconButton(
                  icon: Icon(Icons.arrow_back,color: Colors.black,),
                  onPressed: () {
                    Navigator.pop(context);
                  }),
              Text("notifications".tr,style: TextStyle(color: Colors.black),),
              Spacer(),
              CoreSession.newNotificationCount > 0 ?
              IconButton(
                  onPressed: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => NotificationPage()),
                    );
                  },
                  icon: Image.asset(
                      'assets/imgs/more_icons/notification.png',
                      color: Variables.color_primary,
                      height: 33,
                      width: 30))
                  :     IconButton(
                  onPressed: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => NotificationPage()),
                    );
                  },
                  icon: Image.asset(
                      'assets/imgs/more_icons/notification.png',
                      color: Variables.color_primary,
                      height: 33,
                      width: 30)),
              IconButton(
                  onPressed: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => MyOrderPage()),
                    );
                  },
                  icon: Image.asset(
                      'assets/imgs/default/cart.png',
                      color: Variables.color_primary,
                      height: 33,
                      width: 30)),
            ],
          ),
          automaticallyImplyLeading: false,),
      body: Container(
          height: size.height,
          child: _notificationsList.length > 0
              ? ListView.builder(
                  itemBuilder: (ctx, index) {
                    return Container(
                        color: _notificationsList[index]['unRead']
                            ? Color.fromRGBO(214, 235, 253, .5)
                            : Colors.white,
                        child: GestureDetector(
                            onTap: () {
                              if (_notificationsList[index]['typeId'] == 2 &&
                                  _notificationsList[index]['orderId'] == "") {
                                this.viewNotificationImage(
                                    _notificationsList[index]);
                              } else if (_notificationsList[index]['typeId'] ==
                                      3 &&
                                  _notificationsList[index]['orderId'] == "") {
                                this.viewNotificationVideo(
                                    _notificationsList[index]);
                              }
                              if (_notificationsList[index]['orderId'] != "") {
                                getOrderDetailsForViewAPI(index);
                              }
                            },
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                if (index == 0 ||
                                    (index > 0 &&
                                        timeago.format(DateTime.parse(
                                                _notificationsList[index]
                                                    ['createdDate'])) !=
                                            timeago.format(DateTime.parse(
                                                _notificationsList[index - 1]
                                                    ['createdDate']))))
                                  Padding(
                                    padding: const EdgeInsets.all(10),
                                    child: Text(
                                      timeago.format(
                                          DateTime.parse(
                                            _notificationsList[index]
                                                ['createdDate'],
                                          ),
                                          locale:
                                              CoreSession.selectedLanguageId ==
                                                      2
                                                  ? 'ar'
                                                  : 'en'),
                                    ),
                                  ),
                                NotificationListItem(_notificationsList[index]),
                              ],
                            )));
                  },
                  itemCount: _notificationsList.length)
              : null),
    );
  }
}
