import 'package:aman_kassa_flutter/core/entity/Goods.dart';
import 'package:aman_kassa_flutter/core/locator.dart';
import 'package:aman_kassa_flutter/core/models/nct_product.dart';
import 'package:aman_kassa_flutter/core/models/product_dao.dart';
import 'package:aman_kassa_flutter/core/route_names.dart';
import 'package:aman_kassa_flutter/core/services/DataService.dart';
import 'package:aman_kassa_flutter/core/services/NctService.dart' show NctService, NctServiceException;
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/kassa_actions.dart';
import 'package:aman_kassa_flutter/redux/actions/setting_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/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/shared_styles.dart';
import 'package:aman_kassa_flutter/views/home/tabs/kassaView/CatalogBottomSheet.dart';
import 'package:aman_kassa_flutter/views/home/tabs/kassaView/ProductAddBottomSheet.dart';
import 'package:aman_kassa_flutter/views/payment/payment_view.dart';
import 'package:aman_kassa_flutter/widgets/components/ProductListItem.dart';
import 'package:barcode_scan2/gen/protos/protos.pb.dart';
import 'package:barcode_scan2/gen/protos/protos.pbenum.dart';
import 'package:barcode_scan2/model/scan_options.dart';
import 'package:barcode_scan2/platform_wrapper.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';

class KassaTab extends StatelessWidget {
  final NavigatorService _navigatorService = locator<NavigatorService>();
  final DialogService _dialogService = locator<DialogService>();
  final DataService _dataService = locator<DataService>();
  final NctService _nctService = locator<NctService>();

  final int index;

  KassaTab(this.index);

  Widget buildItem(BuildContext ctxt, int index, ProductDao productDao) {
    return ProductListItem(
      item: productDao,
      index: index,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: Container(
        padding: EdgeInsets.only(bottom: 65.0, left: 8.0),
        child: Align(
          alignment: Alignment.bottomLeft,
          child: FloatingActionButton(
            elevation: 3.0,
            onPressed: scan,
            child: Icon(
              MdiIcons.barcode,
              size: 30,
            ),
          ),
        ),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
      body: Padding(
        padding: const EdgeInsets.all(4),
        child: Column(
          children: <Widget>[
            Row(
              children: <Widget>[
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.all(4.0),
                    child: ElevatedButton(
                      style: ElevatedButton.styleFrom(backgroundColor: primaryColor, padding: const EdgeInsets.all(8)),
                      child: Text(
                        "Добавить",
                        style: buttonBigTitleTextStyle,
                      ),
                      onPressed: () {
                        showModalBottomSheetCatalog(context, 'add');
                      },
                    ),
                  ),
                ),
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.all(4.0),
                    child: ElevatedButton(
                      style: ElevatedButton.styleFrom(backgroundColor: greenColor, padding: EdgeInsets.all(8)),
                      child: Text(
                        "Каталог",
                        style: buttonBigTitleTextStyle,
                      ),
                      onPressed: () {
                        showModalBottomSheetCatalog(context, 'catalog');
                      },
                    ),
                  ),
                ),
              ],
            ),
            Expanded(
              child: Container(
                child: StoreConnector<AppState, KassaState>(
                    converter: (store) => store.state.kassaState!,
                    builder: (context, vm) {
                      return ListView.builder(
                          itemCount: vm.kassaItems!.length,
                          itemBuilder: (BuildContext ctxt, int index) =>
                              buildItem(ctxt, index, vm.kassaItems![index]));
                    }),
              ),
            ),
            //Divider(),
            Container(
              margin: const EdgeInsets.symmetric(vertical: 8),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: <Widget>[
                  StoreConnector<AppState, KassaState>(
                      converter: (store) => store.state.kassaState!,
                      builder: (context, vm) {
                        return Text(totalCalc(vm.kassaItems!),
                            style: TextStyle(fontSize: 25));
                      }),
                ],
              ),
            ),
            Row(
              children: <Widget>[
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.all(4.0),
                    child: ElevatedButton(
                        style: ElevatedButton.styleFrom(backgroundColor: redColor, padding: const EdgeInsets.all(8)),
                        child: Text(
                          "возврат",
                          style: buttonBigTitleTextStyle,
                        ),
                        onPressed: () {
                          _navigatorService.push(PaymentViewRoute,
                              arguments: PaymentModel(
                                  mode: SettingModeKassa,
                                  operationType: OperationTypeReturn));
                        }),
                  ),
                ),
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.all(4.0),
                    child: ElevatedButton(
                      style: ElevatedButton.styleFrom(backgroundColor: greenColor, padding: const EdgeInsets.all(8)),
                      child: Text(
                        "оплата",
                        style: buttonBigTitleTextStyle,
                      ),
                      onPressed: () {
                        _navigatorService.push(PaymentViewRoute,
                            arguments: PaymentModel(
                                mode: SettingModeKassa,
                                operationType: OperationTypePay));
                      },
                    ),
                  ),
                ),
              ],
            )
          ],
        ),
      ),
    );
  }

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

  Future<void> scan() async {
    try {
      await Redux.store!.dispatch(changePinSkipFromSetting(true));
      var options = ScanOptions(strings: {
        "cancel": 'Отмена',
        "flash_on": 'Вкл фонарик',
        "flash_off": 'Выкл фонарик',
      });
      var result = await BarcodeScanner.scan(options: options);
      // print(result.type); // The result type (barcode, cancelled, failed)
      // print(result.rawContent); // The barcode content
      // print(result.format); // The barcode format (as enum)
      // print(result.formatNote); // If a unknown format was scanned this field contains a note
      // print(result.rawContent); // content
      if (result.type == ResultType.Barcode ) {
        String? barcode;
        String? dataMatrix;
        if(result.format == BarcodeFormat.ean13 || result.format == BarcodeFormat.ean8) {
          barcode = result.rawContent;
        } else if( result.format == BarcodeFormat.dataMatrix ) {
          dataMatrix = result.rawContent;
          if(dataMatrix!= null && dataMatrix.length >15) {
            try {
              String numberText = dataMatrix.substring(0, dataMatrix.length - 15 ).replaceAll(RegExp("[a-zA-Z]"), '');
              barcode = int.parse(numberText).toString();
            } catch (e) {

            }
          }
          // 00000046208262 nZ2qnLH ODVFWktT
          // 00000046208262 tjKDqfu UzVSeFE5
        }

        if(barcode != null) {
          List<Good> goods =
              await _dataService.getGoodsByBarcode(barcode: barcode);
          if (goods != null && goods.isNotEmpty) {
            await Redux.store!.dispatch(addProductToKassaItems(goods.first, dataMatrix));
          } else {
            try {
              List<NctProduct> nctResults = await _nctService.searchByNtin(barcode);
              if (nctResults.isNotEmpty) {
                final NctProduct nctProduct = nctResults.first;
                final String? name = nctProduct.nameRu ?? nctProduct.nameKk;
                _openAddSheetWithName(name, ntinCode: nctProduct.ntinCode);
              } else {
                _dialogService.showDialog(description: 'Товар не найден: $barcode');
              }
            } on NctServiceException catch (e) {
              _dialogService.showDialog(description: e.message);
            } catch (e) {
              _dialogService.showDialog(description: 'Ошибка поиска NCT: $e');
            }
          }
        } else if (result.type == ResultType.Error) {
          _dialogService.showDialog(description: 'Не верный формат QR кода');
        }
    }
    } on PlatformException catch (e) {
      var result = ScanResult.create();
      result.type = ResultType.Error;
      result.format = BarcodeFormat.unknown;
      if (e.code == BarcodeScanner.cameraAccessDenied) {
        result.rawContent = 'The user did not grant the camera permission!';
        _dialogService.showDialog(
            description: 'Нет доступа до камеры устройства');
      } else {
        result.rawContent = 'Unknown error: $e';
        _dialogService.showDialog(description: 'Неизвестная ошибка: $e');
      }
    } finally {
      await Redux.store!.dispatch(changePinSkipFromSetting(false));
    }
  }



  void _openAddSheetWithName(String? name, {String? ntinCode}) {
    _navigatorService.navigateToPage(
        MaterialPageRoute(builder: (_) => ProductAddBottomSheet(initialName: name, initialNtinCode: ntinCode))
    );
  }

  void showModalBottomSheetCatalog(BuildContext context, String action) {

    if (action == 'add') {
      Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => ProductAddBottomSheet())
      );
    } else {
      Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => CatalogBottomSheet())
      );
    }

    // showModalBottomSheet(
    //     context: context,
    //     isScrollControlled: true,
    //     backgroundColor: Colors.transparent,
    //     builder: (context) {
    //       return DraggableScrollableSheet(
    //         initialChildSize: 0.8,
    //         maxChildSize: 0.95,
    //         minChildSize: 0.5,
    //         builder: (BuildContext context, ScrollController scrollController) {
    //           if (action == 'add') {
    //             return ProductAddBottomSheet(
    //               scrollController: scrollController,
    //             );
    //           } else {
    //             return CatalogBottomSheet(
    //               scrollController: scrollController,
    //             );
    //           }
    //         },
    //       );
    //     });
  }
}
