import 'package:aman_kassa_flutter/core/locator.dart';
import 'package:aman_kassa_flutter/core/models/calc_model.dart';
import 'package:aman_kassa_flutter/core/models/product_dao.dart';
import 'package:aman_kassa_flutter/core/models/response.dart';
import 'package:aman_kassa_flutter/core/route_names.dart';
import 'package:aman_kassa_flutter/core/services/BankService.dart';
import 'package:aman_kassa_flutter/core/services/DataService.dart';
import 'package:aman_kassa_flutter/core/services/dialog_service.dart';
import 'package:aman_kassa_flutter/core/services/navigator_service.dart';
import 'package:aman_kassa_flutter/redux/actions/calc_actions.dart';
import 'package:aman_kassa_flutter/redux/actions/kassa_actions.dart';
import 'package:aman_kassa_flutter/redux/actions/user_actions.dart';
import 'package:aman_kassa_flutter/redux/constants/operation_const.dart';
import 'package:aman_kassa_flutter/redux/constants/setting_const.dart';
import 'package:aman_kassa_flutter/redux/state/bank_state.dart';
import 'package:aman_kassa_flutter/redux/state/calc_state.dart';
import 'package:aman_kassa_flutter/redux/state/kassa_state.dart';
import 'package:aman_kassa_flutter/redux/store.dart';
import 'package:aman_kassa_flutter/shared/app_colors.dart';
import 'package:aman_kassa_flutter/shared/ui_helpers.dart';
import 'package:aman_kassa_flutter/views/check/image_show_container.dart';
import 'package:aman_kassa_flutter/widgets/components/calculator/calculator.dart';
import 'package:aman_kassa_flutter/widgets/fields/busy_button.dart';
import 'package:aman_kassa_flutter/widgets/loader/Dialogs.dart';
import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';

class PaymentView extends StatefulWidget {
  final PaymentModel model;

  const PaymentView({Key key, this.model}) : super(key: key);

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

class _PaymentViewState extends State<PaymentView> {
  final GlobalKey<State> _keyLoader = new GlobalKey<State>();
  final DataService _dataService = locator<DataService>();
  final DialogService _dialogService = locator<DialogService>();
  BankService _bankService = locator<BankService>();
  final NavigatorService _navigatorService = locator<NavigatorService>();
  bool isBusy;
  bool isBankApiAccess;

  @override
  void initState() {
    super.initState();
    isBusy = false;
    isBankApiAccess = false;
    _bankInit();
  }

  _bankInit() async {
    int version = await _bankService.version();
    if(version>=24){
      setState(() {
        isBankApiAccess = true;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () {
        if (!isBusy) Navigator.pop(context);
        return new Future(() => false);
      },
      child: Scaffold(
        appBar: AppBar(
          brightness: Brightness.light,
          backgroundColor: whiteColor,
          elevation: 0,
          leading: IconButton(
            icon: Icon(Icons.arrow_back_ios),
            color: Colors.black87,
            onPressed: () => Navigator.pop(context),
          ),
          title: Text(
            dataTitle(),
            style: TextStyle(color: Colors.black87),
          ),
        ),
        body: Container(
          padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 12.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(
                dataText(),
                style: TextStyle(
                    fontWeight: FontWeight.bold,
                    color: Colors.black26,
                    fontSize: 15),
              ),
              buildStoreConnector(),
              verticalSpaceLarge,
              _buildBodyContent(),
            ],
          ),
        ),
      ),
    );
  }

  String dataTitle() =>
      widget.model.operationType == OperationTypePay ? 'Оплата' : 'Возврат';

  String dataText() => widget.model.operationType == OperationTypePay
      ? 'К оплате'
      : 'К возврату';

  StoreConnector buildStoreConnector() {
    if (widget.model.mode == SettingModeCalc) {
      return StoreConnector<AppState, CalcState>(
          converter: (store) => store.state.calcState,
          builder: (_, vm) {
            return Text('${totalCalc(vm.calcItems)} тнг',
                style: TextStyle(
                    fontWeight: FontWeight.bold,
                    color: Colors.black87,
                    fontSize: 35));
          });
    }
    return StoreConnector<AppState, KassaState>(
        converter: (store) => store.state.kassaState,
        builder: (_, vm) {
          return Text('${totalKassa(vm.kassaItems)} тнг',
              style: TextStyle(
                  fontWeight: FontWeight.bold,
                  color: Colors.black87,
                  fontSize: 35));
        });
  }

  Expanded _buildBodyContent() {
    return Expanded(
      child: Column(
        children: <Widget>[
          Container(
            height: 150,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                Expanded(
                    child: BusyButton(
                  title: 'Оплатить картой',
                  onPressed: () {
                    pressPayment('card');
                  },
                  mainColor: greenColor,
                )),
                horizontalSpaceSmall,
                Expanded(
                    child: BusyButton(
                  title: 'Наличными',
                  onPressed: () {
                    pressPayment('cash');
                  },
                  mainColor: primaryColor,
                )),
              ],
            ),
          ),
          verticalSpaceLarge,
          _nfsButtonRender(),
          verticalSpaceLarge,
          Expanded(
            child: Container(),
          ),
          Container(
              child: BusyButton(
            title: 'Отмена',
            onPressed: () {
              Navigator.pop(context);
            },
            mainColor: redColor,
          )),
        ],
      ),
    );
  }

  Widget _nfsButtonRender() {
    if(!isBankApiAccess){
      return Container();
    }
    return StoreConnector<AppState, BankState>(
      converter: (store) => store.state.bankState,
      builder: (_, state) {
        if(state.password == null || state.login == null || state.password.length < 1  || state.login.length < 1 ){
          return Container();
        }
        return InkWell(
              onTap: () {
                _navigatorService.push(PaymentNfcViewRoute,
                    arguments: widget.model);
              },
              splashColor: primaryColor.withOpacity(0.4),
              borderRadius: BorderRadius.circular(9.0),
              highlightColor: primaryColor.withOpacity(0.1),
              child: Container(
                padding: const EdgeInsets.all(8.0),
                decoration: BoxDecoration(
                  border: Border.all(color: primaryColor),
                  borderRadius: BorderRadius.circular(9.0)
                ),
                child: Column(
                  children: [
                    Icon(
                      MdiIcons.nfc,
                      color: primaryColor,
                      size: ScreenUtil().setSp(60.0),
                    ),
                    Text('Tap2Phone',style: TextStyle(fontSize: ScreenUtil().setSp(10.0), color: primaryColor),),
                  ],
                ),
              ),
            );
      }
    );
  }

  pressPayment(String type) async {
    setState(() {
      isBusy = true;
    });
    Dialogs.showLoadingDialog(context, _keyLoader);
    try {
      AppState _state = Redux.store.state;
      String _token = _state.userState.user.token;
      String _tradeType = _state.settingState.tradeType;
      String _mode = _state.settingState.mode;
      if (_mode == SettingModeCalc) {
        _tradeType = SettingTradeTypeGood;
      }
      List<ProductDao> kassaItems = _state.kassaState.kassaItems;
      List<CalcModel> calcItems = _state.calcState.calcItems;
      Response<dynamic> response = await _dataService.sellOrReturn(
          token: _token,
          kassaItems: kassaItems,
          paymentType: type,
          operationType: widget.model.operationType,
          tradeType: _tradeType,
          calcItems: calcItems,
          mode: _mode);
      setState(() {
        isBusy = false;
      });
      if (response != null) {
        if (response.operation) {
          String message = response.body['message'];
          String check = response.body['check'];
          String url = response?.body['link'];
          print('url : $url');
          if (_mode == SettingModeCalc) {
            Redux.store.dispatch(cleanCalcItems);
          } else if (_mode == SettingModeKassa) {
            Redux.store.dispatch(cleanKassaItems);
          }
          Redux.store.dispatch(checkMoney);
          Redux.store.dispatch(openSmenaPseudo);
          Navigator.of(_keyLoader.currentContext, rootNavigator: true).pop();
          _navigatorService.pop();
          _navigatorService.push(ImageShowRoute,
              arguments: ImageShowModel(data: check, title: message, url: url));
        } else if (!response.operation &&
            ![401, 402, 403, 412, 500].contains(response.status)) {
          Navigator.of(_keyLoader.currentContext, rootNavigator: true).pop();
          _dialogService.showDialog(description: response.body['message']);
        } else {
          Navigator.of(_keyLoader.currentContext, rootNavigator: true).pop();
        }
      } else {
        Navigator.of(_keyLoader.currentContext, rootNavigator: true).pop();
      }
    } catch (e) {
      print(e);
      Navigator.of(_keyLoader.currentContext, rootNavigator: true).pop();
    } finally {
      //Navigator.of(context, rootNavigator: true).pop();
      setState(() {
        isBusy = false;
      });
    }
  }

  String totalKassa(List<ProductDao> kassaItems) {
    num total = 0.0;
    kassaItems.forEach((element) {
      total += element.total == null ? 0.0 : element.total.toDouble();
    });
    return total.toString();
  }

  String totalCalc(List<CalcModel> items) {
    num total = 0.0;
    items.forEach((element) {
      if (element.operation == Calculations.MULTIPLY) {
        double num1 = element.num1 == null ? 0.0 : double.parse(element.num1);
        double num2 = element.num2 == null ? 0.0 : double.parse(element.num2);
        total += num1 * num2;
      } else {
        total += element.num1 == null ? 0.0 : double.parse(element.num1);
      }
    });
    return total.toString();
  }
}

class PaymentModel {
  String operationType;
  String mode;

  PaymentModel({this.mode, this.operationType});
}
