import 'dart:convert';

import 'package:aman_kassa_flutter/core/entity/Voucher.dart';
import 'package:aman_kassa_flutter/core/locator.dart';
import 'package:aman_kassa_flutter/core/models/check_image_modal.dart';
import 'package:aman_kassa_flutter/core/models/halyk/close_day_data.dart' as halyk_models;
import 'package:aman_kassa_flutter/core/models/forte/close_day_data.dart' as forte_models;
import 'package:aman_kassa_flutter/core/models/halyk/halyk_close_day_dao.dart';
import 'package:aman_kassa_flutter/core/models/forte/forte_close_day_dao.dart';
import 'package:aman_kassa_flutter/core/models/money.dart';
import 'package:aman_kassa_flutter/core/models/response.dart';
import 'package:aman_kassa_flutter/core/models/dialog_models.dart';
import 'package:aman_kassa_flutter/core/models/user.dart';
import 'package:aman_kassa_flutter/core/route_names.dart';
import 'package:aman_kassa_flutter/core/services/ApiService.dart';
import 'package:aman_kassa_flutter/core/services/BankService.dart';
import 'package:aman_kassa_flutter/core/services/ForteService.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/user_actions.dart';
import 'package:aman_kassa_flutter/redux/actions/setting_actions.dart';
import 'package:aman_kassa_flutter/redux/constants/setting_const.dart';
import 'package:aman_kassa_flutter/redux/state/setting_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/fields/aman_icon_button.dart';
import 'package:aman_kassa_flutter/widgets/fields/aman_icon_button_horizontal.dart';
import 'package:aman_kassa_flutter/widgets/fields/busy_button.dart';
import 'package:aman_kassa_flutter/widgets/loader/Dialogs.dart';
import 'package:aman_kassa_flutter/views/payment/halyk_pos_service.dart' as halyk;
import 'package:aman_kassa_flutter/views/payment/forte_pos_service.dart' as forte;
import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';

import '../../../redux/state/bank_state.dart';

class AdditionalTab extends StatefulWidget {
  final int index;

  AdditionalTab(this.index);

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

class _AdditionalTabState extends State<AdditionalTab> {
  ApiService _api = locator<ApiService>();
  NavigatorService _navigator = locator<NavigatorService>();
  DialogService _dialog = locator<DialogService>();
  dynamic _bankService;
  DataService _dataService = locator<DataService>();
  final GlobalKey<State> _keyLoader = new GlobalKey<State>();

  late bool isMoneyCheckBusy;
  late bool closeSmenaBusy;
  late bool openSmenaBusy;
  late bool depositBusy;
  late bool withdrawalBusy;
  late bool xReportBusy;
  late bool updateCatalog;
  late bool isClosePosBusy;

  @override
  void initState() {
    super.initState();
    isMoneyCheckBusy = false;
    closeSmenaBusy = false;
    openSmenaBusy = false;
    depositBusy = false;
    withdrawalBusy = false;
    xReportBusy = false;
    updateCatalog = false;
    isClosePosBusy = false;
  }

  void _closeSmena() async {
    setState(() {
      closeSmenaBusy = true;
    });
    try {
      await Redux.store!.dispatch(closeSmena);
    } catch (e) {
      print(e);
    } finally {
      setState(() {
        closeSmenaBusy = false;
      });
    }
  }

  void _openSmena() async {
    setState(() {
      openSmenaBusy = true;
    });
    try {
      await Redux.store!.dispatch(openSmena);
    } catch (e) {
      print(e);
    } finally {
      setState(() {
        openSmenaBusy = false;
      });
    }
  }

  void _xReport() async {
    setState(() {
      xReportBusy = true;
    });
    try {
      User user = Redux.store!.state.userState!.user!;
      Response response = await _api.xReport(user.token!);
      if (response.operation) {
        String check = response.body['check'];
        var checkText = response.body['check_text'];
        _navigator.push(ImageShowRoute,
            arguments:
                ImageShowModel(data: CheckImageModal(base64Data: check, textData: checkText !=null ? jsonEncode(checkText) : null ), title: 'X Отчет'));

        String? url = response.body['link'];
        _dataService.insertVoucher(
            user: user,
            name: 'X Отчет',
            base64Data: response.body['check'],
            type: VoucherTypeReport,
            url: url);
      } else {
        _dialog.showDialog(description: response.body['message']);
      }
    } catch (e) {
      print(e);
    } finally {
      setState(() {
        xReportBusy = false;
      });
    }
  }

  void _updateCatalog() async {
    setState(() {
      updateCatalog = true;
    });
    try {
      Dialogs.showLoadingDialog(context, _keyLoader);
      await _dataService.getDataFromServer(Redux.store!.state.userState!.user!);
      Navigator.of(_keyLoader.currentContext!, rootNavigator: true).pop();
    } catch (e) {
      print(e);
    } finally {
      setState(() {
        updateCatalog = false;
      });
    }
  }

  void _deposit() async {
    setState(() {
      depositBusy = true;
    });
    try {
      DialogResponse response = await _dialog.showConfirmationDialogInput(
        description: 'Укажите сумму',
        cancelTitle: 'Отмена',
        confirmationTitle: 'Взнос',
      );
      if (response.confirmed) {
        Response<dynamic> result = await _api.deposit(
            Redux.store!.state.userState!.user!.token!, response.responseText!);
        _dialog.showDialog(description: result.body['message']);
        if (result.operation) {
          await Redux.store!.dispatch(checkMoney);
        }
      }
    } catch (e) {
      print(e);
    } finally {
      setState(() {
        depositBusy = false;
      });
    }
  }

  void _withdrawal() async {
    setState(() {
      withdrawalBusy = true;
    });
    try {
      DialogResponse response = await _dialog.showConfirmationDialogInput(
        description: 'Укажите сумму',
        cancelTitle: 'Отмена',
        confirmationTitle: 'Снятие',
      );
      if (response.confirmed) {
        Response<dynamic> result = await _api.withdrawal(
            Redux.store!.state.userState!.user!.token!, response.responseText!);
        _dialog.showDialog(description: result.body['message']);
        if (result.operation) {
          await Redux.store!.dispatch(checkMoney);
        }
      }
    } catch (e) {
      print(e);
    } finally {
      setState(() {
        withdrawalBusy = false;
      });
    }
  }

  void _checkMoney() async {
    setState(() {
      isMoneyCheckBusy = true;
    });
    try {
      await Redux.store!.dispatch(checkMoney);
      setState(() {
        isMoneyCheckBusy = false;
      });
    } catch (e) {
      print(e);
      setState(() {
        isMoneyCheckBusy = false;
      });
    }
  }

  void _closeDay() async {

    setState(() {
      isClosePosBusy = true;
    });

    BankState? state = Redux.store?.state.bankState;

    if (state?.sessionType == 'Halyk' && state?.session != null) {
      _bankService = locator<BankService>();
    } else if (state?.sessionType == 'Forte' && state?.session != null) {
      _bankService = locator<ForteService>();
    }

    int version = await _bankService.version();
    if (version < _bankService.sdkVersion ) {
      setState(() {
        isClosePosBusy = false;
      });
      _dialog.showDialog(description: 'Функция Tap2Phone доступна c Android версии 8.1');
      return;
    }
    final isForteSessionActive = state?.sessionType == 'Forte';

    await Redux.store!.dispatch(changePinSkipFromSetting(true));

    dynamic closeDayDao;
    if (isForteSessionActive) {
      closeDayDao = await forte.closeDayFortePos();
    } else {
      closeDayDao = await halyk.closeDayHalykPos();
    }
    await Redux.store!.dispatch(changePinSkipFromSetting(false));

    forte.log.i(closeDayDao.toJson());
    halyk.log.i(closeDayDao.toJson());

    if (closeDayDao?.result?.code != 0) {
      if (closeDayDao!.result?.description != null) {
        _dialog.showDialog(description: closeDayDao.result!.description!);
      }
      setState(() {
        isClosePosBusy = false;
      });
      return;
    }

    User user = Redux.store!.state.userState!.user!;

    if (isForteSessionActive) {
      final closeDayData = _bankService.closeDayDataConvert(closeDayDao!.transactions!);

      _dataService.insertVoucher(
          user: user,
          name: closeDayData.title!,
          data: jsonEncode(closeDayData.toJson()),
          total: closeDayData.totalAmount!.toDouble(),
          type: VoucherTypeCloseDayPosReport);
    } else {
      final closeDayData = _bankService.closeDayDataConvert(closeDayDao!.transactions!);

      _dataService.insertVoucher(
          user: user,
          name: closeDayData.title!,
          data: jsonEncode(closeDayData.toJson()),
          total: closeDayData.totalAmount!.toDouble(),
          type: VoucherTypeCloseDayPosReport);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: ListView(
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.only(
              top: 10.0,
              left: 20.0,
              right: 20.0,
            ),
            child: StoreConnector<AppState, SettingState>(
                converter: (store) => store.state.settingState!,
                builder: (context, vm) {
                  return Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Flexible(
                          flex: 1,
                          child: AmanIconButtonHorizontal(
                            icon: MdiIcons.calculator,
                            title: 'Калькулятор',
                            selected: vm.mode == SettingModeCalc,
                            onPressed: () => changeMode(false),
                          )),
                      Center(
                          child: Switch(
                        value: vm.mode == SettingModeKassa,
                        onChanged: changeMode,
                        inactiveThumbColor: primaryColor,
                        activeColor: primaryColor,
                      )),
                      Flexible(
                          flex: 1,
                          child: AmanIconButtonHorizontal(
                              icon: MdiIcons.cashRegister,
                              title: 'Режим кассы',
                              selected: vm.mode == SettingModeKassa,
                              onPressed: () => changeMode(true))),
                    ],
                  );
                }),
          ),
          Divider(),
          verticalSpaceMedium,
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Row(
                      children: [
                        Icon(Icons.money, color: primaryColor),
                        Text(
                          'Денег в кассе:',
                          style: TextStyle(color: primaryColor, fontSize: 15),
                        ),
                      ],
                    ),
                    SizedBox(
                      height: 50,
                      // width: double.infinity,
                      child: StoreConnector<AppState, Money>(
                          converter: (store) => store.state.userState!.money!,
                          builder: (_, vm) {
                            if (vm.loading == true) {
                              return Center(
                                child: SizedBox(
                                  width: 30,
                                  height: 30,
                                  child: Padding(
                                    padding: const EdgeInsets.all(8.0),
                                    child: CircularProgressIndicator(
                                      strokeWidth: 2,
                                      valueColor:
                                          new AlwaysStoppedAnimation<Color>(
                                              primaryColor),
                                    ),
                                  ),
                                ),
                              );
                            }
                            return Center(
                              child: Text(
                                vm.total != null
                                    ? '${vm.total} тенге'
                                    : 'нет информации',
                                style: TextStyle(
                                    color: vm.total != null
                                        ? primaryColor
                                        : Colors.grey.withOpacity(0.5),
                                    fontSize: 25,
                                    fontWeight: FontWeight.bold),
                              ),
                            );
                          }),
                    ),
                  ],
                ),
                Container(
                  child: AmanIconButton(
                      title: 'Обновить',
                      onPressed: _checkMoney,
                      busy: isMoneyCheckBusy,
                      icon: Icons.replay_circle_filled,
                      mainColor: primaryColor,
                    ),
                ),
              ],
            ),
          ),
          verticalSpaceMedium,
          Wrap(
            //mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            //crossAxisAlignment: CrossAxisAlignment.start,
            runAlignment: WrapAlignment.center,
            alignment: WrapAlignment.spaceEvenly,
            crossAxisAlignment: WrapCrossAlignment.start,
            children: <Widget>[
              AmanIconButton(
                title: 'Открыть смену',
                onPressed: _openSmena,
                mainColor: greenColor,
                busy: openSmenaBusy,
                icon: Icons.lock_open,
              ),
              AmanIconButton(
                title: 'Закрыть смену',
                onPressed: _closeSmena,
                mainColor: redColor,
                busy: closeSmenaBusy,
                icon: Icons.lock_outline,
              ),
              // AmanIconButton(
              //   title: 'Денег в кассе',
              //   onPressed: _checkMoney,
              //   busy: isMoneyCheckBusy,
              //   icon: MdiIcons.walletOutline,
              //   mainColor: primaryColor,
              // ),
              AmanIconButton(
                title: 'Закрыть POS',
                onPressed: _closeDay,
                busy: isClosePosBusy,
                icon: Icons.phonelink_lock_outlined,
                mainColor: purpleColor,
              ),
              AmanIconButton(
                title: 'Х Отчет',
                onPressed: _xReport,
                busy: xReportBusy,
                mainColor: primaryColor,
                icon: Icons.description,
              ),
              AmanIconButton(
                title: 'История чеков',
                onPressed: () {
                  _navigator.push(HistoryViewRoute);
                },
                mainColor: yellowColor,
                icon: MdiIcons.history,
              ),
              AmanIconButton(
                title: 'Обновить номенклатуру',
                onPressed: _updateCatalog,
                busy: updateCatalog,
                mainColor: greenColor,
                icon: MdiIcons.databaseRefresh,
              ),
            ],
          ),
          verticalSpaceMedium,
          Container(
            margin:
                const EdgeInsets.only(left: 20.0, right: 20.0, bottom: 20.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                Flexible(
                  flex: 1,
                  child: BusyButton(
                    title: 'Взнос наличных',
                    onPressed: _deposit,
                    busy: depositBusy,
                  ),
                ),
                horizontalSpaceSmall,
                Flexible(
                  flex: 1,
                  child: BusyButton(
                    title: 'Снятие наличных',
                    onPressed: _withdrawal,
                    mainColor: redColor,
                    busy: withdrawalBusy,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  void changeMode(el) {
    Redux.store!.dispatch(changeModeFromSetting(el));
  }
}
