import 'package:driverapp/config/config.dart';
import 'package:driverapp/config/size_config.dart';
import 'package:driverapp/core/enum/viewstate.dart';
import 'package:driverapp/core/model/scan_qr/scan_qr_request_model.dart';
import 'package:driverapp/core/service/delivery_tracking_services.dart';
import 'package:driverapp/core/viewModels/authentication_view_model.dart';
import 'package:driverapp/core/viewModels/orders_view_model.dart';
import 'package:driverapp/locator.dart';
import 'package:driverapp/pages/delivery/information_page.dart';
import 'package:driverapp/pages/orders/deliverd_orders_page.dart';
import 'package:driverapp/pages/orders/pending_orders_page.dart';
import 'package:driverapp/pages/setting/setting_page.dart';
import 'package:driverapp/uitl/app_toast.dart';
import 'package:driverapp/uitl/translations_delegate_base.dart';
import 'package:driverapp/uitl/utils.dart';
import 'package:driverapp/widgets/order/order_info_card.dart';
import 'package:driverapp/widgets/others/app_scaffold_widget.dart';
import 'package:driverapp/widgets/others/network_base_view.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_barcode_scanner/flutter_barcode_scanner.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:provider/provider.dart';
import 'package:sweetalert/sweetalert.dart';

import '../base/base_view.dart';

class DashboardScreen extends StatefulWidget {
  @override
  _DashboardScreenState createState() => _DashboardScreenState();
}

class _DashboardScreenState extends State<DashboardScreen> {
  bool _isInit = false;
  AuthenticationViewModel _authenticationViewModel;
  OrdersViewModel _ordersViewModel;

  @override
  void didChangeDependencies() {
    if (!_isInit) {
      _authenticationViewModel = Provider.of(context);
      _isInit = true;
    }

    super.didChangeDependencies();
  }

  @override
  void initState() {
    super.initState();
    // TODO  return it
    Utils.getLocation();
  }

  checkActiveDelivery() async{
    if(_ordersViewModel.orders.isNotEmpty){
      await Future.delayed(Duration(milliseconds: 200));
      var orderNos = await _ordersViewModel.getActiveDeliveringOrders();
      if(orderNos.isEmpty) return;

      int orderNo = int.parse(orderNos.first);
      var order =  _ordersViewModel.orders.firstWhere((element) => element.ePharmacyOrderNo == orderNo, orElse: (){ });
      if(order == null){
        // clear active deliveries if accidentally mismatched during some activity
        _ordersViewModel.deliveryService.clearActiveDeliveringOrders();
        return;
      }
      delay(300, (){
        SweetAlert.show(context, subtitle: "You already have active delivery", confirmButtonText: "Continue Delivery", onPress: (isConfirm){
          pop(context, (){
            Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (context) => InformationPage(
                      item: order,
                    )));
          });
          return false;
        });
      });
    }
  }

  @override
  Widget build(BuildContext context) {

    return BaseView<OrdersViewModel>(
      onModelReady: (model) async {
        _ordersViewModel = model;
        await model.getPendingOrders(1);
        checkActiveDelivery();
      },
      builder: (BuildContext context, OrdersViewModel model, Widget child) =>
          AppScaffold(
            body: SingleChildScrollView(
              child: Container(
                height: MediaQuery.of(context).orientation == Orientation.landscape
                    ? MediaQuery.of(context).size.height * 1.6
                    : MediaQuery.of(context).size.height * 1.0,
                child: Column(
                  children: <Widget>[
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Padding(
                          padding: EdgeInsets.all(16.0),
                          child: Column(
                            children: <Widget>[
                              SafeArea(
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Text(
                                      TranslationBase.of(context).haveGreatDay,
                                      style: TextStyle(
                                          fontSize: 14.5,
                                          color: Color(0xff636363),
                                          fontWeight: FontWeight.w300),
                                    ),
                                    Padding(
                                      padding: EdgeInsets.only(top: 4.5),
                                      child: Text(
                                        _authenticationViewModel.user.userName,
                                        style: TextStyle(
                                            fontSize: 22.0,
                                            color: HexColor("#343333"),
                                            fontWeight: FontWeight.bold),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.all(16.0),
                          child: SafeArea(
                            child: Column(
                              children: <Widget>[
                                InkWell(
                                  child: CircleAvatar(
                                    radius: 25.5,
                                    backgroundColor: Color(0xff30B7B9),
                                    child: CircleAvatar(
                                      backgroundColor: Color(0xff30B7B9),
                                      maxRadius: 26.0,
                                      child: Image.asset(
                                        'assets/images/driver.png',
                                        fit: BoxFit.contain,
                                      ),
                                    ),
                                  ),
                                  onTap: () {
                                    Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                            builder: (context) => SettingPage(
                                                driverName: _authenticationViewModel
                                                    .user.userName,
                                                driverID: _authenticationViewModel
                                                    .user.userID)));
                                  },
                                ),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                    Row(
                      children: <Widget>[
                        Expanded(
                          child: Column(
                            children: <Widget>[
                              Padding(
                                padding: EdgeInsets.symmetric(horizontal: 10.0),
                                child: Container(
                                  height: MediaQuery.of(context).orientation ==
                                      Orientation.portrait
                                      ? MediaQuery.of(context).size.height * 0.16
                                      : MediaQuery.of(context).size.height * 0.30,
                                  width: MediaQuery.of(context).size.width * 0.44,
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(15.0),
                                    gradient: LINEAR_GRADIENT,
                                  ),
                                  child: InkWell(
                                    onTap: () => Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                            builder: (context) =>
                                                OrdersListScreen())),
                                    child: Row(
                                      mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                      children: <Widget>[
                                        Expanded(
                                          child: Padding(
                                            padding: EdgeInsets.all(2.0),
                                            child: Column(
                                              mainAxisAlignment:
                                              MainAxisAlignment.spaceEvenly,
                                              children: <Widget>[
                                                Text(
                                                  TranslationBase.of(context)
                                                      .youHave,
                                                  style: TextStyle(
                                                    color: Colors.white,
                                                    fontSize: MediaQuery.of(context)
                                                        .orientation ==
                                                        Orientation.landscape
                                                        ? SizeConfig
                                                        .textMultiplier *
                                                        2.2
                                                        : SizeConfig
                                                        .textMultiplier *
                                                        1.3,
                                                  ),
                                                ),
                                                Text(
                                                  model.listCountUnDelivered
                                                      .toString(),
                                                  style: TextStyle(
                                                      color: Colors.white,
                                                      fontSize: SizeConfig
                                                          .textMultiplier *
                                                          3.0),
                                                ),
                                                Text(
                                                  TranslationBase.of(context)
                                                      .undeliveredPackages,
                                                  style: TextStyle(
                                                    color: Colors.white,
                                                    fontSize: MediaQuery.of(context)
                                                        .orientation ==
                                                        Orientation.landscape
                                                        ? SizeConfig
                                                        .textMultiplier *
                                                        2.2
                                                        : SizeConfig
                                                        .textMultiplier *
                                                        1.3,
                                                  ),
                                                )
                                              ],
                                            ),
                                          ),
                                        ),
                                        Padding(
                                          padding: EdgeInsets.only(right: 9.5),
                                          child: Container(
                                            width: 100,
                                            height: 100,
                                            decoration: BoxDecoration(
                                                color: Colors.white10,
                                                shape: BoxShape.circle),
                                            child: Column(
                                              mainAxisAlignment:
                                              MainAxisAlignment.center,
                                              children: <Widget>[
                                                Image.asset(
                                                  'assets/images/closed_box.png',
                                                  height: MediaQuery.of(context)
                                                      .orientation ==
                                                      Orientation.portrait
                                                      ? MediaQuery.of(context)
                                                      .size
                                                      .height *
                                                      0.09
                                                      : MediaQuery.of(context)
                                                      .size
                                                      .height *
                                                      0.20,
                                                  width: MediaQuery.of(context)
                                                      .size
                                                      .width *
                                                      0.20,
                                                  scale: 0.9,
                                                  fit: BoxFit.contain,
                                                ),
                                              ],
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              )
                            ],
                          ),
                        ),
                        Expanded(
                          child: Column(
                            children: <Widget>[
                              Padding(
                                padding: EdgeInsets.symmetric(horizontal: 10.0),
                                child: Container(
                                  height: MediaQuery.of(context).orientation ==
                                      Orientation.portrait
                                      ? MediaQuery.of(context).size.height * 0.16
                                      : MediaQuery.of(context).size.height * 0.30,
                                  width: MediaQuery.of(context).size.width * 0.45,
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(15.0),
                                    gradient: LINEAR_GRADIENT,
                                  ),
                                  child: InkWell(
                                    onTap: () => Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                            builder: (context) =>
                                                DeliverdOrdersPage())),
                                    child: Row(
                                      mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                      children: <Widget>[
                                        Expanded(
                                          child: Padding(
                                            padding: EdgeInsets.all(2.0),
                                            child: Column(
                                              mainAxisAlignment:
                                              MainAxisAlignment.spaceEvenly,
                                              children: <Widget>[
                                                Text(
                                                  TranslationBase.of(context)
                                                      .youHave,
                                                  style: TextStyle(
                                                    color: Colors.white,
                                                    fontSize: MediaQuery.of(context)
                                                        .orientation ==
                                                        Orientation.landscape
                                                        ? SizeConfig
                                                        .textMultiplier *
                                                        2.2
                                                        : SizeConfig
                                                        .textMultiplier *
                                                        1.3,
                                                  ),
                                                ),
                                                Text(
                                                  model.listCountDelivered
                                                      .toString(),
                                                  style: TextStyle(
                                                      color: Colors.white,
                                                      fontSize: SizeConfig
                                                          .textMultiplier *
                                                          3.0),
                                                ),
                                                Text(
                                                  TranslationBase.of(context)
                                                      .deliveredPackages,
                                                  style: TextStyle(
                                                    color: Colors.white,
                                                    fontSize: MediaQuery.of(context)
                                                        .orientation ==
                                                        Orientation.landscape
                                                        ? SizeConfig
                                                        .textMultiplier *
                                                        2.2
                                                        : SizeConfig
                                                        .textMultiplier *
                                                        1.3,
                                                  ),
                                                )
                                              ],
                                            ),
                                          ),
                                        ),
                                        Padding(
                                          padding: EdgeInsets.only(right: 9.5),
                                          child: Container(
                                            width: 100,
                                            height: 100,
                                            decoration: BoxDecoration(
                                              color: Colors.white10,
                                              shape: BoxShape.circle,
                                            ),
                                            child: Column(
                                              mainAxisAlignment:
                                              MainAxisAlignment.center,
                                              children: <Widget>[
                                                Image.asset(
                                                  'assets/images/opend_box.png',
                                                  height: MediaQuery.of(context)
                                                      .orientation ==
                                                      Orientation.portrait
                                                      ? MediaQuery.of(context)
                                                      .size
                                                      .height *
                                                      0.09
                                                      : MediaQuery.of(context)
                                                      .size
                                                      .height *
                                                      0.20,
                                                  width: MediaQuery.of(context)
                                                      .size
                                                      .width *
                                                      0.20,
                                                  scale: 0.9,
                                                  fit: BoxFit.contain,
                                                ),
                                              ],
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              )
                            ],
                          ),
                        ),
                      ],
                    ),
                    Padding(
                      padding:
                      EdgeInsets.symmetric(vertical: 16.0, horizontal: 15.0),
                      child: Row(
                        children: <Widget>[
                          Expanded(
                            child: InkWell(
                              onTap: () {
                                _scanQrAndGetPatient(context, model);
                              },
                              child: Container(
                                height: MediaQuery.of(context).orientation ==
                                    Orientation.portrait
                                    ? MediaQuery.of(context).size.height * 0.18
                                    : MediaQuery.of(context).size.height * 0.30,
                                width: MediaQuery.of(context).size.width * 0.50,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(15.0),
                                  gradient: LINEAR_GRADIENT,
                                ),
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                                  children: <Widget>[
                                    Column(
                                      mainAxisAlignment: MainAxisAlignment.center,
                                      children: <Widget>[
                                        Image.asset(
                                          'assets/images/qr_code.png',
                                          width: MediaQuery.of(context).size.width *
                                              0.26,
                                          height: MediaQuery.of(context)
                                              .orientation ==
                                              Orientation.portrait
                                              ? MediaQuery.of(context).size.height *
                                              0.14
                                              : MediaQuery.of(context).size.height *
                                              0.28,
                                          fit: BoxFit.contain,
                                        )
                                      ],
                                    ),
                                    Column(
                                      mainAxisAlignment:
                                      MainAxisAlignment.spaceEvenly,
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: <Widget>[
                                        Padding(
                                          padding: EdgeInsets.only(top: 8.0),
                                          child: Text(
                                            TranslationBase.of(context).scan,
                                            style: TextStyle(
                                              fontSize: MediaQuery.of(context)
                                                  .orientation ==
                                                  Orientation.landscape
                                                  ? SizeConfig.textMultiplier * 6.0
                                                  : SizeConfig.textMultiplier * 4.0,
                                              color: Colors.white,
                                              fontWeight: FontWeight.w400,
                                            ),
                                          ),
                                        ),
                                        Padding(
                                          padding: EdgeInsets.only(top: 0.0),
                                          child: Text(
                                            TranslationBase.of(context)
                                                .toAddPackageToQue,
                                            style: TextStyle(
                                              fontSize: MediaQuery.of(context)
                                                  .orientation ==
                                                  Orientation.landscape
                                                  ? SizeConfig.textMultiplier * 3.0
                                                  : SizeConfig.textMultiplier * 2.0,
                                              color: Colors.white,
                                              letterSpacing: 0.2,
                                              wordSpacing: 0.5,
                                            ),
                                          ),
                                        ),
                                      ],
                                    )
                                  ],
                                ),
                              ),
                            ),
                          )
                        ],
                      ),
                    ),
                    Padding(
                      padding:
                      EdgeInsets.symmetric(horizontal: 20.0, vertical: 1.0),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Column(
                            children: <Widget>[
                              Text(TranslationBase.of(context).nearestDropOffs,
                                  style: TextStyle(
                                      fontSize: 18.0,
                                      color: HexColor("#343333"),
                                      fontWeight: FontWeight.bold)),
                            ],
                          ),
                          if (model.state == ViewState.Idle)
                            Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[
                                InkWell(
                                  child: Row(
                                    children: <Widget>[
                                      Text(
                                        TranslationBase.of(context).seeAll,
                                        style: TextStyle(
                                            fontSize: 14.5,
                                            color: Color(0xff42B6AD)),
                                      ),
                                      Icon(
                                        Icons.arrow_forward_ios,
                                        size: 15.0,
                                        color: Color(0xff42B6AD),
                                      ),
                                    ],
                                  ),
                                  onTap: () => Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                        builder: (context) => OrdersListScreen()),
                                  ),
                                ),
                              ],
                            ),
                        ],
                      ),
                    ),
                    if (model.state == ViewState.Idle && model.orders.length == 0)
                      Padding(padding: EdgeInsets.only(top:20), child: Text("There's No Orders To deliver"),),

                    NetworkBaseView(
                      baseViewModel: model,
                      child: Expanded(
                        child: RefreshIndicator(
                          onRefresh: () async {
                            return await _ordersViewModel.getPendingOrders(1);
                          },
                          child: ListView.builder(
                            shrinkWrap: true,
                            scrollDirection: Axis.vertical,
                            itemCount: model.orders == null
                                ? 0
                                : model.orders.length < 3
                                ? model.orders.length
                                : 3,
                            itemBuilder: (BuildContext context, int index) {
                              return Padding(
                                padding: EdgeInsets.symmetric(horizontal: 0.2),
                                child: OrderInfoCard(
                                  order: model.orders[index],
                                  isActiveToDeliver: _ordersViewModel.isActiveDeliveringOrder(index),
                                  onTap: () {
                                    Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                            builder: (context) => InformationPage(
                                              item: model.orders[index],
                                            )));
                                  },
                                ),
                              );
                            },
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
    );
  }

  _scanQrAndGetPatient(BuildContext context, OrdersViewModel model) async {
    String barcodeScanRes;

    try {
      barcodeScanRes = await FlutterBarcodeScanner.scanBarcode(
          "#ff6666", "Cancel", true, ScanMode.QR);
      print(barcodeScanRes);
      ScanQrRequestModel _scanQrRequestModel = ScanQrRequestModel(
          deliveryOrderID: int.parse(barcodeScanRes), groupID: 0);
      String patientType = "1";
      await model.insertOrder(_scanQrRequestModel);
      if (model.state == ViewState.ErrorLocal) {
        Utils.showErrorToast(model.error);
      } else {
        /// we  call the service ag
        /// ain in order to get them oreder
        await model.getPendingOrders(1);
        AppToast.showSuccessToast(message: "Order Added");
      }
    } on PlatformException {
      Utils.showErrorToast("Failed to get platform version.");
      // barcodeScanRes = 'Failed to get platform version.';
    }
  }
}
