import 'dart:ui';

import 'package:aman_kassa_flutter/core/locator.dart';
import 'package:aman_kassa_flutter/core/services/ApiService.dart';
import 'package:aman_kassa_flutter/core/services/dialog_service.dart';
import 'package:aman_kassa_flutter/redux/actions/user_actions.dart';
import 'package:aman_kassa_flutter/redux/constants/auth_type_const.dart';
import 'package:aman_kassa_flutter/redux/state/user_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/widgets/fields/busy_button.dart';
import 'package:aman_kassa_flutter/widgets/fields/input_field.dart';
import 'package:barcode_scan2/gen/protos/protos.pb.dart';
import 'package:barcode_scan2/model/scan_options.dart';
import 'package:barcode_scan2/platform_wrapper.dart';
import 'package:flutter/services.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:flutter/material.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';

class LoginView extends StatefulWidget {
  final LoginModel? loginModel;

  LoginView({this.loginModel});

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

class _LoginViewState extends State<LoginView> {
  late TextEditingController emailController;

  late TextEditingController passwordController;

  final FocusNode passwordNode = new FocusNode();

  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

  final DialogService _dialogService = locator<DialogService>();

  final ApiService _apiService = locator<ApiService>();

  @override
  void initState() {
    super.initState();
    if (widget.loginModel != null &&
        widget.loginModel?.authType == AuthenticateTypeLogin) {
      emailController = TextEditingController(text: widget.loginModel?.login);
      passwordController =
          TextEditingController(text: widget.loginModel?.password);
    } else {
      emailController = TextEditingController();
      passwordController = TextEditingController();
    }
  }

  @override
  void dispose() {
    emailController.dispose();
    passwordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return StoreConnector<AppState, UserState>(
        converter: (store) => store.state.userState!,
        builder: (context, vm) {
          return Scaffold(
            key: _scaffoldKey,
            backgroundColor: fillColor,
            body: SingleChildScrollView(
              physics: BouncingScrollPhysics(),
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 50),
                child: Column(
                  mainAxisSize: MainAxisSize.max,
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    verticalSpaceLarge,
                    Stack(
                      alignment: Alignment.bottomLeft,
                      children: <Widget>[
                        SizedBox(
                          height: 150,
                          child: Image.asset('assets/images/logo.png'),
                        ),
                        Positioned(
                          child: Text(
                            'онлайн касса',
                            style: TextStyle(fontWeight: FontWeight.bold),
                          ),
                          bottom: 23.0,
                          left: 25.0,
                        ),
                      ],
                    ),

                    InputField(
                      placeholder: 'Электронная почта',
                      controller: emailController,
                      textInputType: TextInputType.emailAddress,
                      nextFocusNode: passwordNode,
                      additionalNote: vm.loginFormMessage?.email,
                    ),
                    verticalSpaceSmall,
                    InputField(
                      placeholder: 'Пароль',
                      password: true,
                      controller: passwordController,
                      fieldFocusNode: passwordNode,
                      additionalNote: vm.loginFormMessage?.password,
                      enterPressed: _pressBtnEnter,
                      textInputAction: TextInputAction.done,
                    ),
                    verticalSpaceMedium,
                    Row(
                      mainAxisSize: MainAxisSize.max,
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        SizedBox(
                          width: 150,
                          child: BusyButton(
                            title: 'Войти',
                            busy: vm.isLoading ?? false,
                            onPressed: _pressBtnEnter,
                          ),
                        )
                      ],
                    ),
                    verticalSpaceLarge,
//                    TextLink(
//                      'Регистрация',
//                      onPressed: () {},
//                    ),
                    IconButton(
                      icon: Icon(MdiIcons.qrcodeScan),
                      iconSize: 40,
                      tooltip: "Scan",
                      onPressed: scan,
                    )
                  ],
                ),
              ),
            ),
          );
        });
  }

  _pressBtnEnter() async {
    if (emailController.text.toLowerCase().trim().startsWith('test')) {
      _apiService.test = true;
    } else {
      _apiService.test = false;
    }
    Redux.store!
        .dispatch(authenticate(emailController.text, passwordController.text));
  }

  Future<void> scan() async {
    try {
      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
      if (result.type == ResultType.Barcode && result.rawContent.length == 60) {
        if (result.rawContent.toLowerCase().trim().startsWith('test')) {
          _apiService.test = true;
        } else {
          _apiService.test = false;
        }
        Redux.store!.dispatch(authenticateToken(result.rawContent));
      } 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');
      }
    }
  }
}

class LoginModel {
  final String? authType;
  final String? login;
  final String? password;

  LoginModel({this.authType, this.login, this.password});
}
