import 'package:echo_app/models/constant-storage.dart';
import 'package:echo_app/models/customer-app-settings-model.dart';
import 'package:echo_app/widgets/checkout_save_box.dart';
import 'package:echo_app/widgets/general_item_list/general_item_list.widget.dart';
import 'package:echo_app/widgets/order_summery_and_edit_dialog/order_summery_and_edit_dialog.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:material_segmented_control/material_segmented_control.dart';
import 'package:rflutter_alert/rflutter_alert.dart';
import 'package:shared_preferences/shared_preferences.dart';

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

// ignore: must_be_immutable
class OrderSummeryPage extends StatefulWidget {
  final bool _isViewOrderHistory;
  final bool _showDeliveredQty;
  var summaryDataList;
  var itemsList;
  var promotedItems;
  var achivements;
  var orderNote;
  double pointDiscountValue;
  Function onSaveOrder;
  LatLng location = LatLng(0.0, 0.0);
  DateTime deliveryDate = new DateTime(
      DateTime.now().year, DateTime.now().month, DateTime.now().day);

  @override
  _OrderSummeryPageState createState() => _OrderSummeryPageState();
  OrderSummeryPage(
      this._isViewOrderHistory,
      this._showDeliveredQty,
      this.summaryDataList,
      this.itemsList,
      this.achivements,
      this.promotedItems,
      this.onSaveOrder,
      this.deliveryDate, this.orderNote, this.pointDiscountValue) {
    if (this.deliveryDate == null) {}
  }
}

class _OrderSummeryPageState extends State<OrderSummeryPage> {
  var orderItems = [];
  var alertStyle = AlertStyle(
    isCloseButton: false,
    alertBorder: RoundedRectangleBorder(
      borderRadius: BorderRadius.circular(0.0),
    ),
  );
  bool showRequired = false;
  bool showDelivered = false;
  bool showQtyInCenter = false;
  initState() {
    if (widget._isViewOrderHistory) {
      this.showRequired = true;
    } else {
      showQtyInCenter = true;
    }
    if (widget._isViewOrderHistory && widget._showDeliveredQty) {
      this.showDelivered = true;
    }

    this.fillSegment();
    if(!this.widget._isViewOrderHistory) this.loadNoteAndDeliveryDate();

    super.initState();
  }

  loadNoteAndDeliveryDate() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {

      this.widget.orderNote =  (prefs.getString(ConstantStorage.note) != null
          ? prefs.getString(ConstantStorage.note)
          : '')!;
      if (prefs.getString(ConstantStorage.deliveryDate) == null ||
          prefs.getString(ConstantStorage.deliveryDate) == '') {
        this.widget.deliveryDate =
            prefs.getString(ConstantStorage.deliveryDate) as DateTime;
      }
    });
  }

  int _currentSelection = 0;
  Map<int, Widget> _titles = {};
  Map<int, Widget> _children = {};

  fillSegment() {
    print("showAchievements${CustomerAppSettingsModel.showAchievements}");
    if (CustomerAppSettingsModel.showAchievements) {
      this._titles = {
        0: Text("items".tr),
        1: Text("free-items".tr),
        2: Text("achievements".tr),
      };
      this._children = {
        0: GeneralItemListWidget(
          this.widget.itemsList,
          this.showRequired,
          this.showDelivered,
          this.showQtyInCenter,
          false,
          null,
          false,
          false,
          null,
          false, 0
        ),
        1: GeneralItemListWidget(
          widget.promotedItems,
          false,
          false,
          true,
          false,
          null,
          false,
          false,
          null,
          false, 0
        ),
        2: GeneralItemListWidget(
          widget.achivements,
          false,
          false,
          true,
          false,
          null,
          false,
          false,
          null,
          false, 0
        ),
      };
    } else {
      this._titles = {
        0: Text("items".tr),
        1: Text("free-items".tr),
      };
      this._children = {
        0: GeneralItemListWidget(
          this.widget.itemsList,
          this.showRequired,
          this.showDelivered,
          this.showQtyInCenter,
          false,
          null,
          false,
          false,
          null,
          false, 0
        ),
        1: GeneralItemListWidget(
          widget.promotedItems,
          false,
          false,
          true,
          false,
          null,
          false,
          false,
          null,
          false, 0
        ),
      };
    }
  }

  getData(DateTime deliveryDate, String orderNote) {
    this.widget.orderNote = orderNote;
    // ignore: unnecessary_null_comparison
    if (deliveryDate != null) {
      this.widget.deliveryDate = deliveryDate;
    }
  }

  onClickInfo() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    Alert(
        useRootNavigator: true,
        context: context,
        style: AlertStyle(
          isCloseButton: false,
          alertBorder: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(5),
          ),
        ),
        title: 'order-summary'.tr,
        content: OrderSummeryAndEditDialog(
            true,
            true,
            widget.summaryDataList,
            this.widget.orderNote,
            this.getData, widget.deliveryDate, widget._isViewOrderHistory ? true : false),
        buttons: [
          if (!widget._isViewOrderHistory)
            DialogButton(
              color: Colors.white,
              child: Text(
                "save".tr,
                style: TextStyle(
                    color: Variables.color_primary, fontSize: 20),
              ),
              onPressed: () => {
                prefs.setString(ConstantStorage.deliveryDate,
                    this.widget.deliveryDate.toString()),
                if (this.widget.orderNote != '')
                  {
                    prefs.setString(ConstantStorage.note, this.widget.orderNote),
                  }
                else
                  {
                    prefs.remove(ConstantStorage.note),
                  },
                Navigator.of(context, rootNavigator: true).pop(),
              },
              width: 120,
            ),
          DialogButton(
            color: Colors.white,
            child: Text(
              "cancel".tr,
              style: TextStyle(color: Colors.red, fontSize: 20),
            ),
            onPressed: () => {
              Navigator.of(context, rootNavigator: true).pop(),
            },
            width: 120,
          )
        ]).show();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
         backgroundColor: Variables.color_primary,
          title: Text(widget._isViewOrderHistory
              ? 'order-details'.tr
              : 'order-summary1'.tr),
          automaticallyImplyLeading: false,
          actions: <Widget>[
            IconButton(
                onPressed: () {
                  onClickInfo();
                },
                icon: Icon(Icons.info_outline)),
            IconButton(
              icon: Icon(Icons.close),
              onPressed: () {
                Navigator.pop(context);
              },
            ),
          ]),
      body: Column(
        children: [
          Expanded(
            flex: 1,
            child: Container(
              width: MediaQuery.of(context).size.width,
              padding: EdgeInsets.symmetric(vertical: 10),
              child: MaterialSegmentedControl(
                children: _titles,
                selectionIndex: _currentSelection,
                borderColor: Variables.color_primary,
                selectedColor: Variables.color_primary,
                unselectedColor: Colors.white,
                borderRadius: 10,
                verticalOffset: 0,
                disabledChildren: [
                  CustomerAppSettingsModel.showAchievements ? 3 : 2
                ],
                onSegmentChosen : (int index) {
                  setState(() {
                    _currentSelection = index;
                  });
                },
              ),
            ),
          ),
          Expanded(
            flex: 9,
            child: Container(
              child: _children[_currentSelection],
            ),
          ),
          Expanded(
            flex: 1,
            child: !widget._isViewOrderHistory
                ? CheckOutSaveBox(double.parse(widget.summaryDataList[0]['netTotal'].toString()),
                    widget.onSaveOrder, 'submit'.tr , true,this.widget.location)
                : Text(''),
          )
        ],
      ),
    );
  }
}
