import 'dart:ui';

import 'package:flutter/services.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
import 'package:satu/core/redux/actions/user_actions.dart';
import 'package:satu/core/redux/state/user_state.dart';
import 'package:satu/core/redux/store.dart';
import 'package:satu/core/services/dialog_service.dart';
import 'package:satu/core/services/navigator_service.dart';
import 'package:satu/core/utils/locator.dart';
import 'package:satu/routes/route_names.dart';
import 'package:satu/shared/app_colors.dart';
import 'package:satu/shared/ui_helpers.dart';
import 'package:satu/widgets/buttons/busy_button.dart';
import 'package:satu/widgets/fields/input_field.dart';
import 'package:satu/widgets/ui/logo.dart';

class LoginView extends StatefulWidget {


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

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

  late TextEditingController passwordController;

  final FocusNode passwordNode = new FocusNode();



  final DialogService _dialogService = locator<DialogService>();

  @override
  void initState() {
    super.initState();
      emailController = TextEditingController(text: 'test11@gmail.com');
      passwordController = TextEditingController();
  }

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

  @override
  Widget build(BuildContext context) {
    return StoreConnector<AppState, UserState>(
        converter: (store) => store.state.userState!,
        builder: (context, vm) {
          return Scaffold(
              body: Column(
                mainAxisSize: MainAxisSize.max,
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  LogoSatu(),
                  InputField(
                    placeholder: 'Введите почту',
                    controller: emailController,
                    textInputType: TextInputType.emailAddress,
                    nextFocusNode: passwordNode,
                  ),
                  verticalSpaceSmall,
                  InputField(
                    placeholder: 'Введите пароль',
                    password: true,
                    controller: passwordController,
                    fieldFocusNode: passwordNode,
                    enterPressed: _pressBtnEnter,
                    textInputAction: TextInputAction.done,
                  ),
                  verticalSpaceMedium,
                  Padding(
                    padding: EdgeInsets.only( left: 45.sp, right: 45.sp, top: 30.sp ),
                    child: BusyButton(
                      title: 'ВОЙТИ',
                      busy: vm.isLoading!,
                      onPressed: _pressBtnEnter,
                    ),
                  ),
                  verticalSpaceLarge,
                  IconButton(
                    icon: Icon(MdiIcons.qrcodeScan),
                    iconSize: ScreenUtil().setSp(40.0),
                    tooltip: "Scan",
                    onPressed: scan,
                  )
                ],
              ));
        });
  }

  Future<void> _pressBtnEnter() async {
    Redux.store!.dispatch(authenticate(emailController.text, passwordController.text));
  }

  Future<void> scan() async {

    final NavigatorService _nav = locator<NavigatorService>().push(addByBarcodeViewRoute) as NavigatorService;
    final dynamic result = await _nav.push(addByBarcodeViewRoute) ;
    if(result != null) {
      if( result.length == 60 ) {
        Redux.store?.dispatch(authenticateByToken(result as String));
      } else {
        _dialogService.showDialog(description: 'Не верный формат QR кода');
      }
    }

    // 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) {
    //     //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({required this.authType, required this.login, required this.password});
}
