import 'package:driverapp/app-icons/driver_app_icons.dart';
import 'package:driverapp/config/config.dart';
import 'package:driverapp/config/size_config.dart';
import 'package:driverapp/core/model/authentication/login_request.dart';
import 'package:driverapp/core/model/orders/pending_orders_res_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/core/viewModels/project_view_model.dart';
import 'package:driverapp/locator.dart';
import 'package:driverapp/pages/authentication/reset_password_page.dart';
import 'package:driverapp/pages/delivery/delivery_confirmed_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/buttons/secondary_button.dart';
import 'package:driverapp/widgets/others/app_scaffold_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:provider/provider.dart';
import 'package:sweetalert/sweetalert.dart';

import 'forget_password_page.dart';

// ignore: must_be_immutable
class DeliveryVerificationPage extends StatelessWidget {

  final PendingOrdersRes order;
  DeliveryVerificationPage({this.order});

  ProjectViewModel _projectViewModel;
  OrdersViewModel _ordersViewModel;
  final formKey = GlobalKey<FormState>();
  Map formValues = {
    'digit1': null,
    'digit2': null,
    'digit3': null,
    'digit4': null,
  };

  FocusNode focusD1 = FocusNode();
  FocusNode focusD2 = FocusNode();
  FocusNode focusD3 = FocusNode();
  FocusNode focusD4 = FocusNode();
  var model;
  TextEditingController digit1 = TextEditingController(text: "");
  TextEditingController digit2 = TextEditingController(text: "");
  TextEditingController digit3 = TextEditingController(text: "");
  TextEditingController digit4 = TextEditingController(text: "");

  bool _isLoading = false;

  SizedBox buildSizedBox([double height = 20]) {
    return SizedBox(
      height: height,
    );
  }

  BuildContext _context;
  @override
  Widget build(BuildContext context) {
    _context = context;
    _projectViewModel = Provider.of(context);
    _ordersViewModel = Provider.of(context);

    String validateCodeDigit(value) {
      if (value.isEmpty) {
        return 'Please enter your Password';
      }

      return null;
    }

    return AnimatedSwitcher(
      duration: Duration(milliseconds: 2000),
      child: AppScaffold(
        isShowAppBar: false,
        body: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              FractionallySizedBox(
                widthFactor: 0.80,
                child: Column(
                  children: <Widget>[
                    SizedBox(
                      height: 30,
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          child: Icon(
                            DriverApp.deliverd_icon,
                            size: 150,
                            color: Theme.of(context).primaryColor,
                          ),
                          margin: EdgeInsets.only(
                            top: 20,
                          ),
                        ),
                      ],
                    ),
                    SizedBox(
                      height: 20,
                    ),
                    Column(
                      children: <Widget>[
                        Center(
                          child: Text(
                            "Verification",
                            style: TextStyle(
                                fontSize: 25,
                                letterSpacing: 1,
                                fontWeight: FontWeight.w600),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(
                      height: 30,
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    Form(
                        key: formKey,
                        child: Container(
                            width: SizeConfig.realScreenWidth * 0.90,
                            child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  Padding(
                                    padding: const EdgeInsets.symmetric(
                                        horizontal: 20),
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.end,
                                      children: <Widget>[
                                        Expanded(
                                          child: Text(
                                            TranslationBase.of(context)
                                                .enterCustomerVerificationCodeMsg,
                                            textAlign: TextAlign.center,
                                            style: TextStyle(
                                                fontSize: 13,
                                                color: Colors.grey),
                                          ),
                                        ),
                                        SizedBox(
                                          height: 10,
                                        )
                                      ],
                                    ),
                                  ),
                                  buildSizedBox(30),
                                  Center(
                                    child: FractionallySizedBox(
                                      widthFactor: 0.80,
                                      child: Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceAround,
                                        children: <Widget>[
                                          Container(
                                            width: 55,
                                            height: 55,
                                            color: Colors.transparent,
                                            child: Center(
                                              child: TextFormField(
                                                textInputAction:
                                                    TextInputAction.next,
                                                style: TextStyle(
                                                  fontSize: SizeConfig
                                                          .textMultiplier *
                                                      3,
                                                ),
                                                focusNode: focusD1,
                                                controller: digit1,
                                                  enableInteractiveSelection: false,
                                                  showCursor: false,
                                                  maxLength: 1,
                                                textAlign: TextAlign.center,
                                                keyboardType:
                                                    TextInputType.number,
                                                decoration:
                                                    buildInputDecoration(
                                                        context),
                                                onSaved: (val) {
                                                  formValues[
                                                      'digit1'] = val;
                                                },
                                                validator: validateCodeDigit,
                                                onFieldSubmitted: (_) {
                                                  FocusScope.of(context)
                                                      .requestFocus(focusD2);
                                                },
                                                onChanged: (val) => val.isNotEmpty
                                                    ?  FocusScope.of(context).requestFocus(focusD2)
                                                    : FocusScope.of(context).requestFocus(focusD1)
                                              ),
                                            ),
                                          ),
                                          Container(
                                            width: 55,
                                            height: 55,
                                            color: Colors.transparent,
                                            child: Center(
                                              child: TextFormField(
                                                focusNode: focusD2,
                                                controller: digit2,
                                                  enableInteractiveSelection: false,
                                                  showCursor: false,
                                                  maxLength: 1,
                                                textInputAction:
                                                    TextInputAction.next,
                                                textAlign: TextAlign.center,
                                                style: TextStyle(
                                                  fontSize: SizeConfig
                                                          .textMultiplier *
                                                      3,
                                                ),
                                                keyboardType:
                                                    TextInputType.number,
                                                decoration:
                                                    buildInputDecoration(
                                                        context),
                                                validator: validateCodeDigit,
                                                onSaved: (val) {
                                                  formValues[
                                                      'digit2'] = val;
                                                },
                                                onFieldSubmitted: (_) {
                                                  FocusScope.of(context)
                                                      .requestFocus(focusD3);
                                                },
                                                onChanged: (val) => val.isNotEmpty
                                                    ?  FocusScope.of(context).requestFocus(focusD3)
                                                    : FocusScope.of(context).requestFocus(focusD1)
                                              ),
                                            ),
                                          ),
                                          Container(
                                              width: 55,
                                              height: 55,
                                              color: Colors.transparent,
                                              child: Center(
                                                child: TextFormField(
                                                  focusNode: focusD3,
                                                  controller: digit3,
                                                  enableInteractiveSelection: false,
                                                  showCursor: false,
                                                  maxLength: 1,
                                                  textInputAction: TextInputAction.next,
                                                  textAlign: TextAlign.center,
                                                  style: TextStyle(
                                                    fontSize: SizeConfig
                                                            .textMultiplier * 3,
                                                  ),
                                                  keyboardType:
                                                      TextInputType.number,
                                                  decoration:
                                                      buildInputDecoration(
                                                          context),
                                                  validator: validateCodeDigit,
                                                  onSaved: (val) {
                                                    formValues[
                                                        'digit3'] = val;
                                                  },
                                                  onFieldSubmitted: (_) {
                                                    FocusScope.of(context)
                                                        .requestFocus(focusD4);
                                                  },
                                                  onChanged: (val)  => val.isNotEmpty
                                                      ?  FocusScope.of(context).requestFocus(focusD4)
                                                      : FocusScope.of(context).requestFocus(focusD2),
                                                ),
                                              )),
                                          Container(
                                            width: 55,
                                            height: 55,
                                            color: Colors.transparent,
                                            child: Center(
                                              child: TextFormField(
                                                  focusNode: focusD4,
                                                  controller: digit4,
                                                  enableInteractiveSelection: false,
                                                  showCursor: false,
                                                  maxLength: 1,
                                                  textAlign: TextAlign.center,
                                                  style: TextStyle(
                                                    fontSize: SizeConfig
                                                            .textMultiplier *
                                                        3,
                                                  ),
                                                  keyboardType:
                                                      TextInputType.number,
                                                  decoration:
                                                      buildInputDecoration(
                                                          context),
                                                  validator: validateCodeDigit,
                                                  onSaved: (val) {
                                                    formValues[
                                                        'digit4'] = val;
                                                  },
                                                  onFieldSubmitted: (_) {
                                                    FocusScope.of(context)
                                                        .requestFocus(focusD4);
                                                  },
                                                  onChanged: (val)  => val.isNotEmpty
                                                      ?  FocusScope.of(context).requestFocus(focusD4)
                                                      : FocusScope.of(context).requestFocus(focusD3)
                                                  ),
                                            ),
                                          )
                                        ],
                                      ),
                                    ),
                                  ),
                                  buildSizedBox(20),
                                  // ShowTimerText(model: model),
                                ])))
                  ],
                ),
              ),
              SizedBox(
                height: 20,
              ),
              SizedBox(
                height: 10,
              ),
              Container(
                  margin: EdgeInsets.all(10),
                  height: MediaQuery.of(context).size.height * 0.22,
                  child: Column(
                    children: <Widget>[
                      SecondaryButton(
                        label: "Verify Receiver",
                        onTap: () {
                          _verifyCustomer();
                        },
                        disabled: _isLoading,
                        loading: _isLoading,
                      ),
                      SizedBox(
                        height: 10,
                      ),
                      // Row(
                      //   mainAxisAlignment: MainAxisAlignment.end,
                      //   children: <Widget>[
                      //     InkWell(
                      //       onTap: () {
                      //         Navigator.pushReplacement(
                      //           context,
                      //           MaterialPageRoute(
                      //               builder: (context) =>
                      //                   ForgetPasswordPage()),
                      //         );
                      //       },
                      //       child: InkWell(
                      //         onTap: () async {
                      //           await _ordersViewModel.resendOtpToReceiver(order);
                      //         },
                      //         child: Text(
                      //           "Resend OPT?",
                      //           style: TextStyle(
                      //               fontSize: 14,
                      //               color: Theme.of(context).primaryColor),
                      //         ),
                      //       ),
                      //     ),
                      //   ],
                      // ),
                    ],
                  ))
            ],
          ),
        ),
      ),
    );
  }

  TextStyle buildTextStyle() {
    return TextStyle(
      fontSize: SizeConfig.textMultiplier * 3,
    );
  }

  InputDecoration buildInputDecoration(BuildContext context) {
    return InputDecoration(
      filled: true,
      fillColor: Colors.white,
      // ts/images/password_icon.png
      contentPadding: EdgeInsets.only(top: 30, bottom: 30),
      enabledBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(10)),
        borderSide: BorderSide(color: Colors.grey),
      ),
      focusedBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(10.0)),
        borderSide: BorderSide(color: Theme.of(context).primaryColor, width: 2),
      ),
      errorBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(10.0)),
        borderSide: BorderSide(color: Theme.of(context).errorColor, width: 2),
      ),
      focusedErrorBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(10.0)),
        borderSide: BorderSide(color: Theme.of(context).errorColor, width: 2),
      ),
        counterText: "",
        errorStyle: TextStyle(height: 0.0)
    );
  }



  _verifyCustomer() async {
    if (formKey.currentState.validate()) {
      final pinCode = digit1.text + digit2.text + digit3.text + digit4.text;
      formKey.currentState.save();

      SweetAlert.show(_context, subtitle: "Please wait...", style: SweetAlertStyle.loading);
      var results = await _ordersViewModel.validateDelivery(order, pinCode);
      if (results != null && results.isSuccessful) {
        results = await _ordersViewModel.updateOrderStatus(orderNo: order.orderID, status: DeliveryStatus.delivered);
        popWithDelay(context: _context, seconds: 0.2, callback: (){
          if(results.isSuccessful){
            _goToDeliveryDoneConfirmation();
          }else{
            Utils.showErrorToast(results.message);
          }
        });

      }else{
        Navigator.of(_context).pop();
        Utils.showErrorToast(results.message);
      }
    }
  }


  _goToDeliveryDoneConfirmation(){
    locator<DeliveryTrackingServices>().stopLocationUpdate(order.ePharmacyOrderNo); // Stop Driver Location update for Order
    Navigator.pushReplacement(
      _context,
      MaterialPageRoute(
        builder: (context) => DeliveryConfirmedPage(order),
      ),
    );
  }
}
